Saturday, July 07, 2007

Advantage of using Properties

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:

Avni said...

Very true..

Properties are basically used when we want to put some condition on value.

Avni said...

Good one

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape