C# .NET - difference between public variable and property in c#

Asked By koteswara rao arvapalli on 26-Dec-12 08:33 AM
difference between public variable and property in c#

Kamal Ramavat replied to koteswara rao arvapalli on 26-Dec-12 08:31 AM

obvious differences

  1. A property can have accessor keywords.

    public string MyString { get; private set; }
    
  2. A property can be overridden in descendents.

    public virtual string MyString { get; protected set; }
Kamal Ramavat replied to Kamal Ramavat on 26-Dec-12 08:36 AM

The fundamental difference is that a field is a position in memory where data of the specified type is stored. A property represents one or two units of code that are executed to retrieve or set a value of the specified type. The use of these accessor methods is syntactically hidden by using a member that appears to behave like a field (in that it can appear on either side of an assignment operation).


Bharatesh Bedke replied to koteswara rao arvapalli on 27-Dec-12 06:31 AM
A public variable is a member variable of the class which is accessible through the object of that class directly.
Which may be harmful sometimes as it can be accessed directly. So to avoid this problem, properties were introduced. Which allows the access of the member variable(In this case declared as private) indirectly.
Also properties allows to do some logic before we could return the value to the caller.