Fields
They are also known as class instance fields, class variables or member variables.
A field is a Variable of any type that is declared directly inside a class or structure.
Fields should not be accessed directly but always through Properties.
The default access modifier is private.
public class Animal
{
private int _Age;
}
Accessing - Using Public
This should never be done as it breaks encapsulation.
Any fields that are declared public, provide clients with direct access to the data without any restrictions.
Any data that you want to expose outside of the class should be accessed through Methods or Properties.
public class Animal
{
public int _Age;
}
Accessing - Using Methods
They are also known as Get methods and Set methods.
It is possible to manage your private fields using public methods as a way of achieving encapsulation.
The challenge here though is to define consistent and easy to remember names for these methods.
public class Animal
{
private int _Age;
public int ReturnAge()
{
return this._Age;
}
public void ChangeAge(int Age)
{
this._Age = Age;
}
}
Accessing - Using Properties
They are also known as read-write properties.
You should always access your private fields using a public property.
Using public properties ensures that all the code is together in one block.
This also has the flexibility to quickly create read-only and write-only fields.
When a private field is exposed using a public property this is known as a backing field or backing store.
This allows you to change the implementation without changing the way the variables are accessed externally.
public class Animal
{
private int _Age;
public int Age
{
get { return this._Age; }
set { this._Age = value; }
}
}
Being Explicit
It is good practice to always use the this. prefix when referring to your private fields.
It is also common to prefix your private variables with an underscore.
This is to avoid any confusion, for example when variables, methods or properties all have the same name.
Volatile Fields
A volatile modifier can be used to indicate that a field can be modified by the operating system, hardware or another concurrently executing thread
The volatile keyword can be applied to fields of the following types
Reference Types (the reference is volatile, not where it actually points to)
Primitive Types
Enumeration Types
public class Animal
{
private volatile int _Age;
}
Any fields that are declared as volatile are not subject to compiler optimisations.
Multi-Threading
You can get unpredictable results when using non-volatile fields in a multi-threaded application.
The compiler will perform optimization techniques on non-volatile fields which can cause unexpected results when using multi-threading.
More Details
© 2026 Better Solutions Limited. All Rights Reserved. © 2026 Better Solutions Limited TopPrevNext