Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#3.0 Automatic properties, why not access the field directly?

With the new approach of having the get/set within the attribut of the class like that :

public string FirstName {
        get; set;
    }

Why simply not simply put the attribute FirstName public without accessor?

like image 755
Pokus Avatar asked Oct 06 '08 13:10

Pokus


2 Answers

Two of the big problems with direct access to variable inside class (field/attribute) are:

1) You can't easily databind against fields.

2) If you expose public fields from your classes you can't later change them to properties (for example: to add validation logic to the setters)

like image 127
Patrick Desjardins Avatar answered Oct 22 '22 09:10

Patrick Desjardins


Because, in the future, if you change the implementation, code using the current interface won't break.

For instance, you implement a simple class with a public field and start using your class in some external modules. A month later you discover you need to implement lazy loading in that class. You would then need to transform the field to a property. From the external module point of ciew, it might look the same syntaxicaly, but it is not. A property is a set of functions, while a field is an offset in a class instance.

By using a property, you effectively reduce the risk the interface will change.

like image 14
Coincoin Avatar answered Oct 22 '22 11:10

Coincoin