Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between Private Fields and Private Properties

What is the difference between using Private Properties instead of Private Fields

private String MyValue { get; set; }  // instead of  private String _myValue;  public void DoSomething() {    MyValue = "Test";     // Instead of     _myValue = "Test"; } 

Is there any performance issue ? or just a naming convention ?

like image 875
Yoann. B Avatar asked Jan 04 '09 14:01

Yoann. B


People also ask

What is difference between fields and properties?

Fields are ordinary member variables or member instances of a class. Properties are an abstraction to get and set their values. Properties are also called accessors because they offer a way to change and retrieve a field if you expose a field in the class as private.

What is a private field?

Private fields are accessible on the class constructor from inside the class declaration itself. They are used for declaration of field names as well as for accessing a field's value. It is a syntax error to refer to # names from out of scope.

What is the difference between a field property and a field in database?

Properties expose fields. Fields should (almost always) be kept private to a class and accessed via get and set properties. Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class.


1 Answers

Private properties allow you to abstract your internal data so that changes to the internal representation don't need to affect other parts of your implementation, even in the same class. Private fields do not offer this advantage. With automatic properties in C# 3.0, I rarely see a need to implement fields directly -- private or public.

like image 96
tvanfosson Avatar answered Sep 20 '22 19:09

tvanfosson