c# - Is it bad style to have a member with the same name as a class? -


suppose have class foo and

class foofrobber {    private foo _foo;     foofrobber(foo foo)    {        _foo = foo;    }     frob()    {       _foo.frobcount += 1;    } } 

it seems _foo name private field, if want make internal or protected variable? convention (http://weblogs.asp.net/lhunt/archive/2004/08/17/csharpcodingstandardsv113.aspx via style guide c#?) seems to use studlycaps no m_ or trailing _, means declare protected foo foo. seems work, seems little bit odd shadowing class name. style guide says fields should private, seems bit excessive (but maybe that's inner python speaking). @ rate, seems have same problem if wanted wrap _foo in property.

should come different name field, in myfoo? ok leave is, compiler doesn't seem mind?

it’s allowed , common practice have fields/properties share same name type. first example comes mind fcl dispatcherobject.dispatcher, returns instance of type dispatcher.

however, prefer avoid declaring fields protected, , use properties instead. if want avoid coding involved declaring backing field, may use auto-implemented property:

protected foo foo { get; set; } 

the advantage of using properties can apply different access modifiers getter , setter:

protected foo foo { get; private set; } 

edit: advantage of using protected properties instead of protected fields allow change implementation – example, introduce value validation or change notification – without breaking external libraries might access it.

suppose, example, want extend class implement inotifypropertychanged. if using protected field, there no straightforward way of detecting when value of field changed consuming assembly (unless change implementation of external assembly well). if using protected property, alter implementation without requiring changes in consuming assemblies:

private foo foo;  protected foo foo  {          {         return foo;     }     set     {         if (foo != value)         {             foo = value;             onpropertychanged("foo");         }     } } 

edit2: several more advantages using properties on fields given in lbushkin’s answer.

changing field property appear break abi. haven’t yet found stated in authoritative source (i didn’t spend time looking); however, per pst’s comment:

the code behind property can changed (to use custom private backing field or whatever). however, changing public member variable property breaking change in abi (application binary interface).

per jstedfast’s answer:

first thing keep in mind property accessors compiled methods. means has different abi reading/writing class member variable, though may syntactically same.


Comments

Popular posts from this blog

jquery - Invalid Assignment Left-Hand Side -

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -