Monday, March 7, 2011

C# - Using auto implemented properties and naming conventions

Hi,

When using auto implemnted properies like

public string MyProperty { get; set; }

This is great until you come to naming conventions.

I use underscore for class level fields ie

string _MyProperty;

so with auto implemented means that it is not obvious what the variable is and it scope.

If you get my meaning, any thoughts??

Malcolm

Edit: As the property is public you dont want to use a underscore either.

From stackoverflow
  • PascalCasing tells you its class level AND public. (Look at this article about naming conventions for .NET)

  • I guess what i am saying is I don't like it.

    Also a follow up question is why not just a public field anyhow what is the difference?

    Arjan Einbu : This should be added as a new question...
  • hi malcolm,

    you don't need the _ at all when you use the automatic properties and a modern IDE (like visual studio). intellisense will work correctly if you use automatic properties and different visibilities. the compiler will also check it.

        public string SomeString { private set; get; }
    
        private string some2string;
    
        public string Some3string { set; get; }
    

    this means that SomeString is only internal writeable. you will not get the property outside of the class. so no magic _ etc.

    if you have a really class-only property, then there is no need to make property, make just a field.

  • The property itself is public. The compiler generates private fields for your property. Since auto implemented properties are not natively supported by MSIL. But because the private fields are generated by the compiler you never have to deal with them directly.

    A great book about naming conventions is Framework Design Guidelines 2nd edition by Brad Abrams. link

    A great tool to enforce naming conventions is Stylecop

  • field / property:

    if you just use "get,set" as in my example, you are right, what should be the difference, but, maybe you will do some additional task if somebody calls the property, or sets the property. maybe you will do some check on setting a property, or updating some internal state of the object.

0 comments:

Post a Comment