Andy Stampor
Andy Stampor

Reputation: 688

What is a good naming convention to differentiate a class name from a property in C#?

I run into this frequently enough that I thought I'd see what others had to say about it.

Using the StyleCop conventions, I find that I often have a property name that is hard to make different than the class name it is accessing. For example:

public class ProjectManager
{
 // Stuff here
}

public class OtherClass
{
     private ProjectManager ProjectManager { get; set; }
}

It compiles and runs, but seems like it would be an easy way to confuse things, even with the use of "this".

Upvotes: 9

Views: 630

Answers (3)

JaredPar
JaredPar

Reputation: 755587

This is actually a very common pattern in .Net programming. Particularly so with enum types and members as it's the .Net Design Guidelines recommended way of programming.

4.0 design guidelines reference

While it may be a bit confusing, it's not once you've seen it a few times. The tools well support this pattern and given one is a type and the other an instance it's hard to accidentally invert them without causing a compilation error.

Upvotes: 11

drharris
drharris

Reputation: 11204

I agree with the other answers. For completeness sake, sometimes I find a way to generalize the class name a bit more. I understand your example was just an example, but one way to do it would be:

public class Person
{
  // Stuff here
}

public class OtherClass
{
  private Person ProjectManager { get; set; }
}

This helps make it a bit more readable. But it is perfectly acceptable (and even encouraged) to have identical class name and property.

Upvotes: 1

John Saunders
John Saunders

Reputation: 161831

That is a typical naming convention when there will only be a single property of type ProjectManager within any given class. It ceases to be confusing because there are no other uses of the ProjectManager type.

Of course, if there are other uses, then you need different names.

Upvotes: 4

Related Questions