Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Honestly, what's the difference between public variable and public property accessor? [duplicate]

Possible Duplicates:
What is the difference between a field and a property in C#
Should I use public properties and private fields or public fields for data?

What is the difference between:

public string varA;

and

public string varA { get; set; }
like image 605
Marin Avatar asked Jun 30 '11 23:06

Marin


2 Answers

The public property accessor gives you more flexibility in the future.

If you want to add validation to setting the value, you simply write a non-default setter. None of your other code would have to be modified.

There could also be reasons you'd want to replace the default getter with code. That can be a real pain with a public variable.

like image 116
jimreed Avatar answered Nov 19 '22 23:11

jimreed


In addition to the other answers, you can also use a property to make the value read-only or even set-only:

public int Item { get; private set; } // read-only outside the class. Can only be set privately.

I have also run into situations where I later decide I want to proxy an object, or add AOP, which basically requires properties.

like image 5
CodingWithSpike Avatar answered Nov 20 '22 01:11

CodingWithSpike