Alex Rivera | Logout

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

Asked 2011-06-30T23:25:46.357
20

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; }
Edit
Report

1 Answer

1

Public property accesses fields and internal class code through exposed getter and setter methods. A public field acesses the field directly.

Using propertys offers the potential to provide a layer of abstraction and design (ability to make set accessor protected, private).

When a property is specified and no body present an underlying private field is created by the compiler that is used to store the value against. Essentially:

private int item = 0;
public int Item {
get { return item; }
set {item = value; }
}

In general I tend to use properties for public exposed variables and fields for private. I might consider using a field if that field was accessed many times and speed was a crucial design requirement.

answered 2011-07-01T00:56:44.967

Your Answer