Difference between fields and properties C# Examples
The class contains fields and properties.
C# is a programming Language that provides OOP features. Classes contain state and behavior.
The class contains variables, properties, and fields
Both are variables defined in the class. The difference is in the use of scope and storage.
Let’s see what is variables and differences.
C# field variables
Fields are variables declared in a class, with private or protected scope. Since Classes encapsulate the data and restrict access outside a class. Fields provide restricted access.
Field variables used in a class or struct
class Employee{
//field variable
private String _name;
}
In the above example _name
is a field that is not accessible outside a class.
Fields can be static or private variables
C# properties variables
Properties are variable fields that expose to external classes via the Set
and Get
methods. It supports encapsulation to hide the internal details.
It protects field variables to read and write using the property
class Employee{
//field variable
private String _name;
// property variable
public string Name {
get { return name; }
set { name = value; }
}
}
val employee = Employee()
employee.name = "Mark" // setter method called
println(employee.name) // getter method called
properties can have an accessor method such as set - to set the value, get - to get the value
public string Name { get; set; }
Difference between Properties and Fields
Properties | Fields |
---|---|
Properties exposed to external | Fields are private to a class |
properties never store the data in | Fields stores the data at class level |
Interface has properties | Interface has not fields variables |
Properties variable contains virtual | Fields has no virtual |
Properties allow fields to read and write | Fields provides memory storage for a class |
Properties might throw exception | Field never throw exception |
Allows Side effects - exception, call methods etc. | does not allow side effects |