开发者

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

开发者 https://www.devze.com 2022-12-31 18:28 出处:网络
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

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 wit开发者_运维知识库h the use of "this".


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

  • http://msdn.microsoft.com/en-us/library/ms229012(v=VS.100).aspx

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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消