Malcolm
Malcolm

Reputation: 12864

C# - Using auto implemented properties and naming conventions

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.

Upvotes: 1

Views: 1282

Answers (4)

karlis
karlis

Reputation: 920

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.

Upvotes: 0

Michael
Michael

Reputation:

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

Upvotes: 0

karlis
karlis

Reputation: 920

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.

Upvotes: 0

Arjan Einbu
Arjan Einbu

Reputation: 13672

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

Upvotes: 5

Related Questions