C# language has a keyword to mention fields in a class can be readonly. In this tutorial let's discuss readonly keyword and how it can be used to convey class author intention that a field value shouldn't be modified once the class instance is created.
C# sample demonstrating readonly keyword
public class Employee
{
private readonly string _id;
public string _deptId;
public Employee(string id)
{
_id = id;
DeptId = deptId;
}
public string ID
{
get
{
return _id;
}
}
public string DeptID
{
get
{
return _deptID;
}
set
{
_deptID =value;
}
}
}
{
private readonly string _id;
public string _deptId;
public Employee(string id)
{
_id = id;
DeptId = deptId;
}
public string ID
{
get
{
return _id;
}
}
public string DeptID
{
get
{
return _deptID;
}
set
{
_deptID =value;
}
}
}
Notes on above C# program
- "_id" has been declared as readonly.
- "_id" member has been assigned a value inside the Employee class constructor.
readonly class members and value assignment
- With readonly members properties, you can assign value only during initialization and inside the class constructors.
- If you try to assign value to members anywhere else, you will get the below error:
A readonly field cannot be assigned to (except in a constructor or a variable initializer)
When to define readonly fields in a class
If a member of a class whose value you(class author) don't want anyone to change post object construction, then consider marking that member as readonly.
By declaring a member as readonly you are indicating to other fellow developers that such member value cannot be changed once the object is created (post constructor call).
No comments:
Post a Comment