Facebook Twitter Gplus LinkedIn YouTube Google Maps RSS
Home Technical Why use properties ?
formats

Why use 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;
}
}

Source: http://dotnetguts.blogspot.com/2007/07/advantage-of-using-properties.html

 
Tags:
 Share on Facebook Share on Twitter Share on Reddit Share on LinkedIn
No Comments  comments 

Leave a Reply

Your email address will not be published. Required fields are marked *

*

* Copy this password:

* Type or paste password here:

12,873 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© All rights reserved to Cyberbrutus. 2012
credit

Switch to our mobile site