Should a property have the same name as its type?

2019-01-06 15:49发布

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).

9条回答
孤傲高冷的网名
2楼-- · 2019-01-06 16:42

I give things the same name as their type, except for case: my methods and properties are "lowerCase"; and I therefore wouldn't have the problem that MiffTheFox has.

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

public class B2
{
    private B1 m_b1;

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

    public void Foo()
    {
        B1.myFunc(); //this is Ok, no need to use namespace
    }
}

So for me, m_b1 is member data, b1 is a property (or a local variable or parameter), and B1 is the name of the class.

查看更多
SAY GOODBYE
3楼-- · 2019-01-06 16:43

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.

查看更多
We Are One
4楼-- · 2019-01-06 16:49

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.

查看更多
登录 后发表回答