Fields and Properties
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
Contents |
Fields
Fields in a class are used to hold data. Fields can be marked as public, private, protected, internal, or protected internal. A field can optionally be declared static. A field can be declared readonly. A read-only field can only be assigned a value during initialization or in a constructor.
A field can be given an initial value by using the assignment operator when the field is declared.
public class Car { public string make = "Ford"; }
Fields are initialized immediately before the constructor for the object instance is called, so if the constructor assigns the value of a field, it will overwrite any value given during field declaration.
public class Car { public string make = "Ford"; public Car() { make = "Alfa"; } }
These examples use fields that are public, but this is not recommended in practice. Fields should generally be private with access to fields given by using properties.
Properties
Properties allow users to access class variables as if they were accessing member fields directly, while actually implementing that access through a class method.
The user wants direct access to the variables of the object and does not want to work with methods. The class designer, however, wants to hide the internal variables of his class in class members, and provide indirect access through a method. By decoupling the class variables from the methods that access those variables, the designer is free to change the internal state of the object as needed.
Coding properties
The code below shows how to create a private variable with its associated properties.
// private member variables private int hour; // create a property public int Hour { get { return hour; } set { hour = value; } }
You then access the properties in the following manner:
// Get the current value of hour to local variable iHour int iHour = aClass.Hour; // Increment iHour iHour++; // Write iHour back to hour aClass.Hour = iHour;
Properties in C# 2.0
In C# 2.0 you can set the accessibility of get and set.
The code below shows how to create a private variable with an internal set and public get. The Hour property can now only be set from code in the same module (dll), but can be accessed by all code that uses the module (dll) that contains the class.
// private member variables private int hour; // create a property public int Hour { get { return hour; } internal set { hour = value; } }
MSDN references
|

