Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

c# - Should a property have the same name as its type?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...