30/09/2018, 22:17
Hỏi về get, set trong C#
Chào mọi người mình xin hỏi 1 chút là khi đã dùng private thì có set, get. thế sao đoạn code dưới đây đã có public rồi sao còn dùng set, get làm gì nữa ạ
public class Book
{
public string ISBN { set; get; }
public string Title { set; get; }
public string Author { set; get; }
public DateTime PublishDate { set; get; }
public string ShowBook()
{
return ISBN + " - " + Title + " - " + Author + " - " + PublishDate ;
}
Bài liên quan
In C# we have Properties that provide the opportunity to protect a field in a class by reading and writing to it through the property. In other languages, this is often accomplished by programs implementing specialized getter and setter methods. C# properties enable this type of protection while also letting you access the property just like it was a field.
Why we use properties instead fields in C#
Just for encapsulation principle. For hinding concrete implementaiton, and plus, you have an opportunity (in this case) to add additional code inside get/set.
https://blogs.msdn.microsoft.com/vbteam/2009/09/04/properties-vs-fields-why-does-it-matter-jonathan-aneja/