Advantage of using Properties
What is Properties?
Attribute of object is called properties. Eg1:- A car has color as property.
Example of using properties in .Net:
private string m_Color;;
public string Color
{
get
{
return m_Color;
}
set
{
m_Color = value;
}
}
Car Maruti = new Car();
Maruti.Color= “White”;
Console.Write(Maruti.Color);
Advantage of using Properties You might have question Isn't it better to make a field public than providing its property with both set { } and get { } block? After all the property will allow the user to both read and modify the field so why not use public field instead?
Not always! Properties are not just to provide access to the fields; rather, they are supposed to provide controlled access to the fields of our class. As the state of the class depends upon the values of its fields, using properties we can assure that no invalid (or unacceptable) value is assigned to the fields. Example explaining how Properties are useful
private int age;
public int Age
{
get
{
return age;
}
set
{
if(value <> 100)
//throw exception
else
age = value;
}
}
2 comments:
Very true..
Properties are basically used when we want to put some condition on value.
Good one
Post a Comment