Friday, January 9, 2009

C# naming convention for constants

When I was working on C++, my naming convention for constants was to be ALL_CAPS. In C# the recommended naming convention for constants is Pascal casing (starts with upper case).

private const int MaxLimit = 100;

Even though it is a private field, it is not a variable and it cannot be accessed using "this" object within your class. Hence I prefer using Pascal casing to differentiate it with variable members, which are in Camel casing (starts with lower case) as per .NET naming convention.

Microsoft has come up with this cool tool named StyleCop that documents all the preferred conventions and it can also check your source code for compliance.

Check out this link for more information on StyleCop.
http://code.msdn.microsoft.com/sourceanalysis

Tuesday, January 6, 2009

C# 3.0 Automatic Property with private set method.

What if we need a automatic property with just a get method (read-only property), like this
public string Name { get; }

Compiler will throw error
"'Employee.Name.get' must declare a body because it is not marked abstract or extern. Automatically implemented properties must define both get and set accessors."

The reason being automatic property requires both get and set method defined. You can fix this error by defining the private set method for the property. By doing this, the property is still just a "getter".

public string Name { get; private set; }