Saturday 5 May 2007

camelCase in C# and the CLR

I want to address the issue of differentiating private fields from public properties using case alone. Everyone knows that the subject is a matter of preference and everyone has a strong argument to support their preference.

My favourite comment on this debate comes from an observer of Brad's series on the Framework Design Guidelines at http://blogs.msdn.com/brada/archive/2005/10/28/486215.aspx .

Ahh, I had gone almost a week without a good Case Sensitivity Holy War. I do love to watch the monkeys fling poo. I feel supporting case insensitive languages is important because it helps give this whole debate even more room to blaze. -Shawn Oster

On a more serious note,
  • The point of differentiating by more than case is CLR compliance.
  • CLR compliance provides interoperability between programming languages within the framework.
  • The rule is that publicly accessible properties must differ by more than case in order to disambiguate references or calls between assemblies on accessible API's.
A private field cannot be accessed by another CLR language. There is therefore no requirement to disambiguate by more than case because no language that would be confused by case sensitivity can access the field in question.

It is my experience that the issue of adding an underscore before private fields usually comes about after a rule in a default code analysis policy file is violated and it barfs an error about CLR compliance. The policy file is at fault, not the code. The policy should first have examined the accessibility of the field in question.

Microsoft's standard internal policy is to use camelCase for private fields and PascalCase for publicly accessible properties (http://blogs.msdn.com/brada/articles/361363.aspx - 2.6 Naming). This is not a violation of the CLR. Furthermore, it makes for far more elegant code.
Consider the following comparison. Underscores are just butt ugly:

private string myString;
public string MyString
{
get { return myString; }
set { myString = value; }
}
------
private string _MyString;
public string MyString
{
get { return _MyString; }
set { _MyString = value; }
}

Please don't make me use underscores...

1 comment:

Unknown said...

Ah progress... I'm so pleased that this whole argument has been made redundant by the Auto-Property feature in C# 3.0.