How do you resolve the common naming collision between type and object?
Since the standard c# convention is to capitalize the first letter of public properties, the old c++ convention of initial capital for type names, and initial lowercase for non-type names does not prevent the classic name collision where the most obvious object name matches the type name:
class FooManager
{
public BarManager BarManager { get; set; } // Feels very wrong.
开发者_如何学运维 // Recommended naming convention?
public int DoIt()
{
// 1st and 2nd Bar Manager are different symbols
return BarManager.Blarb + BarManager.StaticBlarb;
}
}
class BarManager
{
public int Blarb { get; set; }
public static int StaticBlarb { get; set; }
}
It seems to compile, but feels so wrong. Is there a recommend naming convention to avoid this?
Having a type and a property with the exact same name isn't uncommon. Yes, it looks a little weird, but renaming properties to avoid this clash looks even weirder, admittedly.
Eric Lippert had a blog post on this exact topic.
There is no ambiguity for the compiler, however.
The c# convention is to name properties in the same way as you name your classes. The reason you feel it's wrong is because you come from a different background. But if you use if for a while you will learn that it doesn't cause you any problems and it will feel pretty natural when you are used to it. There is no place when it will collide in any way. I (as a c# developer) feel that the convention of initial lower case letter for properties feel wrong. You just have to get used to it.
I'm okay with this honestly -- if your static methods/members aren't obviously static by name and by purpose, you've got bigger problems than name collision.
I do not think it has ever caused an issue for me. Following are general conventions, for Properties. Only thing helpful
could be getting used
to these....
- Pascal Case, no underscores.
- Try to avoid abbreviations.
- Members must differ by more than case to be usable from case-insensitive languages like Visual Basic .NET.
Why: This convention is consistent with the .NET Framework and is easy to read. like
public int RecordId
reference : NET Programming Standards and Naming Conventions
also check this: General Naming Conventions
I will caviat this by saying, I don't mind the collision, as the compiler can work it out. However, in the spirit of offering other solutions I have seen, and letting others decide for myself... I think this is where the ugly (to me) pattern of using My* arose.
For instance:
public class Foo { /* ... */ }
public class Bar
{
public Foo MyFoo { get; set; }
// ...
}
精彩评论