C#.NET
will support three types of properties. ,
1. Read
only Property
2. Write
only Proper
3. Read
Write Property
1) Read only Property
- This property is used to read the data from the Data field
- We can’t write the Data into data field using this property
- This property will contain only one accessor i.e., get Accessor
Access
Modifier Data Type Property Name
{
get
{
return Data Filed Name;
}
}
2) Write only Property
:-
- This is used to write the data into Data field of a class
- Using this property, we can’t read the data from the data field
- This property will contain only one accessor i.e. set accessor
Access
Modifier Data Type Property Name
{
set
{
Data Field Name=value;
}
}
3) Read Write Property
:-
- This is used to read the data from the Data Field and to write the Data into the Data Field
- This property will contain two accessors i.e. get and set
Syntax :-
Access Modifier Data Property Name
{
set
{
Data Filed Name=value;
}
get
{
return Data Filed Name;
}
}
- Whenever, we create property, the Data type of a property must and should be same as the Data type of the Data field into which we want to transfer the data
- A property can never accept Arguments
- Declaration of variables or writing the code outside the accessors within the property is prohibited
Advantages of Properties
- Properties will provide abstraction to the Data fields
- Properties will provide security to the Data fields
- Properties can be used to validate the data before allowing a change
Symmetric and Asymmetric
Accessors
By
default Accessors of Assessors is same as the Accessibility of the property
Ex:
public
int PEmpId
{
set
{
EmpId=value;
}
get
{
return EmpId;
}
}
- In the above property, property PEmpId is declared as public, so set and get will be public
- If property is private, then set and get will be private
- Symmetric Assessors: If the accessibility of the Accessors are same, then accessors are known as Symmetric Accessors
- Asymmetric Accessors: If the Accessibility of the Accessors is not same, then Assessors are known as Asymmetric
Example
public
int PEmpId
{
protected set
{
EmpId=value;
}
get
{
return EmpId;
}
}
- In the above example set is protected and get is public. So they are known as Asymmetric
- In general Asymmetric accessors are used in Inheritance process
- We can also write the Read Only Property using two accessors like
public
int PEmpId
{
set
{
EmpId=value;
}
private get
{
return EmpId;
}
}
public
int PEmpId
{
private set
{
EmpId=value;
}
get
{
return EmpId;
}
}
No comments:
Post a Comment