Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Sorry If I am being noob, I have this doubt, why do we use private variables and set them using properties ?

Why can't we just use properites alone ?

I am talking about situations like this

private string _testVariable;

public string MyProperty
{
    get { return _testVariable;}
    set {_testVariable = value;}
}

I am thinking of simply using

public string MyProperty { get; set; } 

Why redundant private variable? are these two strategies different ? can anyone please throw some light on this.

Thanks

See Question&Answers more detail:os

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

1 Answer

Your examples are semantically the same. The concise property declaration syntax (just having { get; set; }) is a shortcut available in C# 3.0. The compiler actually creates a private backing variable and a simple getter and setter as in your first example.

If all you're doing is creating a getter and setter (and nothing actually happens when either occurs), then the concise syntax is a good option. If you have to perform any other actions (redraw a control, for example) when you set the value, then the full syntax is required.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...