Should a property have the same name as its type?

33,789

Solution 1

It's fine. The canonical example here is

public Background {
    public Color Color { get; set; }
}

There are rare issues (corner cases) that come up here, but not enough to warrant avoiding this device. Frankly, I find this device quite useful. I would not enjoy not being able to do the following:

class Ticker { ... }


public StockQuote {
    public Ticker Ticker { get; set; }
}

I don't want to have to say Ticker StockTicker or Ticker ThisTicker etc.

Solution 2

The Microsoft Naming Guideline for Members state:

Consider giving a property the same name as its type.

When you have a property that is strongly typed to an enumeration, the name of the property can be the same as the name of the enumeration. For example, if you have an enumeration named CacheLevel, a property that returns one of its values can also be named CacheLevel.

Though I admit there is a little ambiguity whether they are just recommending this for Enums or for properties in general.

Solution 3

I can only think of one drawback. If you wanted to do something like this:

public class B1
{
        public static void MyFunc(){ ; }
}

public class B2
{
        private B1 b1;

        public B1 B1
        {
                get { return b1; }
                set { b1 = value; }
        }

        public void Foo(){
                B1.MyFunc();
        }
}

You'd have to instead use:

MyNamespace.B1.MyFunc();

A good example of this is common usage is in Winforms programming, where the System.Windows.Forms.Cursor class overlaps with the System.Windows.Forms.Form.Cursor property, so your form events have to access static members using the full namespace.

Solution 4

Just today, Eric blogged about the 'Color Color' problem.

http://blogs.msdn.com/ericlippert/archive/2009/07/06/color-color.aspx

Personally, I would avoid it if possible.

Solution 5

Another gotcha is with inner types.

I run into this one all the time:

public class Car {
    public enum Make {
        Chevy,
        Ford
    };

    // No good, need to pull Make out of the class or create
    // a name that isn't exactly what you want
    public Make Make {
        get; set;
    }
}
Share:
33,789

Related videos on Youtube

Moe Sisko
Author by

Moe Sisko

Updated on July 05, 2022

Comments

  • Moe Sisko
    Moe Sisko almost 2 years

    I've sometimes seen code written like this :

    public class B1
    {
    }
    
    public class B2
    {
        private B1 b1;
    
        public B1 B1
        {
            get { return b1; }
            set { b1 = value; }
        }
    }
    

    i.e. class B2 has a property named "B1", which is also of type "B1".

    My gut instinct tells me this is not a good idea, but are there any technical reasons why you should avoid giving a property the same name as its class ?

    (I'm using .net 2.0, in case that matters).

    • niico
      niico over 7 years
      which naming convention - calling them the same thing, or changing case for differentiation?
  • Steven Sudit
    Steven Sudit almost 15 years
    Why? I don't see any harm to it.
  • Timothy Walters
    Timothy Walters almost 15 years
    Unfortunately using lower-case for Properties and Methods is in direct conflict with the accepted naming guidelines for C#.
  • ChrisW
    ChrisW almost 15 years
    Yes. They're inferior guidelines, IMO, don't you agree? Why did they come to be?
  • jason
    jason over 14 years
    class A { public static void Method(int i) { } public void Method(object o) { } } and class B { A A { get; set; } public B() { A = new A(); A.Method(0); } }. Is A.Method calling the static method named Method or is it calling the instance method named Method? (In C# it turns out that it will call the static method. However, if you replace the 0 in A.Method(0) by "Hello, world!" it will call the instance method. Note that Intellisense doesn't pick this up and will highlight the A in A.Method("Hello, world!") blue as if it were the static method.)
  • jason
    jason over 14 years
    And this is merely to point out that there can be (rare) cases wherein the intent of the code using this pattern is not crystal clear (there is, of course, always an unambiguous interpretation based on the language specification).
  • Hand-E-Food
    Hand-E-Food over 12 years
    Which is why I pluralise my enum names. There are several possible Makes of car, but this car has only one Make. It doesn't always read the best, but I look at is as the enum being a list of possible Makes.
  • Jason S
    Jason S over 12 years
    @jason Properties I agree, but objects why? Don't you want to distinguish your static (class) method calls from your instance calls? If you have one object, I see no reason for A = new A(), just do a = new A(). It is no more onerus but much clearer. Your edge case concerns objects, not properties. However you closed the question concerning objects. In VB, intellisense and renaming do not distinguish between class and instance references when object and class are the same name. But renaming properties with same name as the type is no problem.
  • Jason S
    Jason S over 12 years
    @Jason See this question for problems to do with renaming in VB projects, when objects are named the same as their class. This does not apply to properties, but my question about naming objects the same as their class, was closed as a duplicate of this one.
  • Jason S
    Jason S over 12 years
    @jason Your edge case also means that if you rename the object reference, A in A=new A() to a for instance, A.Method("Hello, world!") will not be renamed, causing a NullReferenceException at runtime. Another reason not to name objects the same as the class, but this is not an issue with properties! Renaming the property with the same name as its return type is not a problem.
  • MasterMastic
    MasterMastic over 11 years
    @StevenSudit IMO it adds complexity for the programmer (after all, you need to read that article to understand what's going on), and we programmers know how bad & error-prone that is. I'd avoid it too.
  • ToolmakerSteve
    ToolmakerSteve almost 6 years
    BTW, this has since become somewhat more of an issue for me, with BindableProperty in WPF or Xamarin Forms. For example, I have a property Font. In defining BindableProperty FontProperty I need to refer both to property Font and to default value Font.Default, which is attempting to refer to class Font, but fails w/o further syntax to disambiguate. Still, its worth the tradeoff.
  • ToolmakerSteve
    ToolmakerSteve almost 6 years
    What his article actually shows is that it is stupid to have both static and instance members with the same name. Which I would hope any programmer would avoid. Note this key sentence "In real situations the instance and static methods typically have different names". Note that the problems all arise because he declared static M and (instance) M. The discussion of Color Color just shows that combining Color Color with static M and M makes the problem worse. So don't do the original idiocy.
  • ToolmakerSteve
    ToolmakerSteve almost 6 years
    Its a trade-off as to which maximizes clarity / minimizes misunderstanding. Consider a typical code file of yours. Count all appearances of all class names, member names, and local variable names. You'll find that class names are a small fraction of the total appearances of named items. So your choice assigns "lowercase" to a strong majority of name appearances. Therefore, you assign a high value to distinguishing "class" from "not class". Nothing wrong with that, but the recommended style instead distinguishes "local" from "not local". Maybe off-balanced in opposite way...
  • Kiruahxh
    Kiruahxh about 3 years
    I end up naming it CarMake. However C# naming convention is quite bad to generate such king of conflicts, We should have members and properties starting with a lowercase, to make them truly interchangeable