Naming convention for private fields

烈酒焚心 提交于 2019-11-29 02:57:05

You are quite right. It doesn't.

Using this is a way to ensure you are using the class member, in case of naming conflicts (say a parameter name that is identical to a field name).

For me, pascal casing public members and camel casing private members has always been enough of a convention to work well.

I strongly prefer the leading "_" convention for private fields, even though it does not follow MS conventions:

  1. It eliminates conflicts with camel cased parameter names - no need to use "this"

  2. It's a visual indicator that the internal persistent state of the object is being read, or - more importantly - being written. It's a flag saying "this has side effects outside of the particular method I happen to be looking at", which is very important to know when looking at unfamiliar code.

Using this.age could help distinguish between the backing store of your Age property and an age parameter for a method on your object:

public bool CheckIfOlderThan(int age)
{
   // in here, just using "age" isn't clear - is it the method parameter? 
   // The internal field?? Using this.age make that clear!
   return (this.age >= age); 
}

Of course, in this case, you could also give your parameter a less confusing name to avoid any clashes....

But in the actual definition of the property - reading and storing its value in the backing store - adding the this. doesn't really add anything. Some people I know just prefer to use the this. prefix all the time - not just when it's needed - personal preference, really...

Prefixing private fields with underscore is basically the same thing as using "this.". However underscore is faster to use, shorter and more elegant to me (this comes from Java I believe).

Having the same names for function parameters and private fields seems a bit tricky to me. Not only once have I forgot to use "this" which resulted in nasty NullPointerException (yes, I did java someday... :) ).

As far as I know it doesn't violate any FxCop rule, as it's not a hungarian notation.

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