What is the correct naming notation for classes, functions, variables etc in c#?

怎甘沉沦 提交于 2019-12-01 19:24:52

Classes should be in camel notation with the first letter capitalized

public class MyClass

Functions and Methods in C# should act in a similar fashion except for private methods

public void MyMethod()
private void myPrivateMethod()

Variables I tend to do a little differently:

Member Variables

private int _count;

Local variables

int count;

You're looking for StyleCop.

I agree on the calculate vs get distinction: get() should be used for values that are already calculated or otherwise trivial to retrieve.

Additionally, I would suggest in many cases adding a noun to the name, so that it's obvious exactly what sum you are calculating. Unless, of course, the noun you would add is the class name or type itself.

All of the above.

I believe the official C# guidelines would say call it calculateSum() as getSum() would be used if the sum was an instance variable. But it depends on the coding style used and how any existing code in the project is written.

Luckily enough I don't believe there is a standardized way this is done. I pick the one that I like, which consequently also seems to be the standard all other source code I've seen uses, and run with it.

Sum() if it's public and does the work itself.

GetSum() if it's public and it retrieves the information from somewhere else.

sum() / getSum() as above, but for internal/private methods.

(Hmm... That's a bit vague, since you shift the meaning of "Sum" there slightly. So, let try this again.

XXX if xxx is a process (summing values). GetXXX if xxx is a thing. (the sum of the values)

Method names are verbs. Class, field and property names are nouns. In this case, Sum could pass as either a verb or a noun...

AddNumbersReturnTotal fits the above definition, but it's a little long. Out of kindness to the guy who gets to maintain my code (usually me!) I try and avoid including redundant words in identifiers, and I try to avoid words that are easy to make typos on.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!