Also known as a Class Field.
A class variable defined with a specific class visibility, usually private visibility. A member property is different than a member field. A member property uses a member field to store values through accessor methods (getters and setters). For example, it is common to use a private member field to store the current value of a property. The current values of all the class member fields is the current state of the object.
Languages Focus: Member Field
What modifiers apply to member fields, if any? Typical member field modifiers include scope modifiers (private, protected, etc.) and read-only. Can you initialize the value of a member field when declared ensuring a default value?
C# Member Field
In C# you can set the visibility of a member field to any visibility: private, protected, public, internal or protected internal.
You can intialize a member field with a default when declared. If you set the member field value in your constructor, it will override the default value.
Finally, you can use the static modifier (no instance required) and readonly modifier (similar to a constant).
Syntax Example: public class Cyborg : System.Object
{
private string serialNumber = "A100";
public string cyborgName;
public int cyborgAge = 0;
public static readonly int seriesID = 100;
}
Member Fields versus Properties
Sometimes it is convenient to use a public member field instead of implementing a member properity. However, you're first choice should be to use a property even when you initially have no additional logic required for accessing the data.
C# 3.0 introduced auto-implemented properties for use when no additional logic is required which means now properties are just as easy to create as a member field and have an equivalent compact form (a single line of code).
pulic int VendorID {get; set;}
For a read-only property, leave out the set method.
The following are practice certification questions with answers highlighted. These questions were prepared by Mike Prestwood and are intended to stress an important aspect of this KB post. All our practice questions are intended to prepare you generally for passing any certification test as well as prepare you for professional work.