Can you tell me what is the exact usage of properties in C# i mean practical explanation
in our project we are using properties like
/// <summary>
/// column order
/// </summary>
protected int m_order;
/// <summary>
/// Get/Set column order
/// </summary>
public int Order
{
get { return m_order; }
set { m_order = value; }
}
/// <summary>
/// constructor
/// </summary>
/// <param name="name">column name</param>
/// <param name="width">column width</param>
/// <param name="order">column order</param>
public ViewColumn(string name, int width, int order)
{
//
// TODO: Add constructor logic here
//
m_name = name;
m_width = width;
m_order = order;
}
/// <summary>
/// returns the column name, width, and order in list view.
/// </summary>
/// <returns>string represent of the ViewColumn object</returns>
public override string ToString()
{
return (string.Format("column name = {0}, width = {1}, order = {2}.",
m_name, m_width, m_order));
}
/// <summary>
/// Do a comparison of 2 ViewColumn object to see if they're identical.
/// </summary>
/// <param name="vc">ViewColumn object for comparison</param>
/// <returns>True if the objects are identical, False otherwise.</returns>
public override bool Equals(object obj)
{
ViewColumn vc = (ViewColumn)obj;
if(m_name == vc.Name &&
m_width == vc.Width &&
m_order == vc.Order)
return true;
else
return false;
}
Design Time Benefits
Properties makes visual designing easy, you have Most Famous Property Browser of Visual Studio to allow you to change properties of object.
Properties also provide additional metadata of validation, visual appearance inside Property Browser, like drop down, range, color picker etc.
Seperate Data and Actions
They truely represent difference between "Data" of object and "Actions" (Methods) of object.
When we look at class, if we have 50 methods to look at, not everyone will always use correct naming of functions, that will make things difficult to understand later on. I always tell the programmers that whenever you program, write the code in such a way that after 5 years, if someone else looks at the code, he should understand the code.
Using method names of data access and some actions create confusion in long run... like in case of Stack, Push/Pop are actions but "Size" or "Count" is data.
Creating property of "Count" simply distinguishes its purpose as data instead of action.
Databinding
As mentioned by others, properties offer advanced level of databinding like two way binding etc.
Access Restrictions
You can have readonly properties and additional accessors as mentioned by others.
Reflection
Its little easy to work with properties in case of writing generic code based on reflection.
Different Storage Implementation
Public variables store data only as members, where else properties provide various ways to store data in different forms like internaly they can be stored as hashtable (as they are done in dependency objects in WPF). They can be cached. They cab be relayed further to some other child entities or foriegn entities. However implementation is hidden for callers.
Validation
Setting property may require certain validation, and validation code in "Set" part of code can easily help you validate the input and report errors accordingly.
Notifications
Set part of method can raise notification events such as INotifyPropertyChanged.PropertyChanged which other objects can listen for and update the display value. This is important part of advanced data binding.
In short, its a new "Standard" of data storage that has advanced facilities then just mere storing the data in the members of class. By avoiding properties typically you can perform all functions, but since implementation may differ from person to person, its a standard which helps everyone to define/access/validate/notify the data storage in one single form called "Properties"
As Justin noted, Encapsulation is one of the basic tenets of OOP. You would want to keep the internal representation of the data in your class hidden from outside and provide approved ways of viewing/manipulating it.
C# properties are constructs that provide an easy way to do that. In your example, you aren't doing anything inside the
get
andset
methods but in real life you may need to do certain things likeIn Java, you write getters and setters which are plain-old methods that return or accept a value respectively.
Properties are used to restrict direct access to member variables of a class. Abstraction is maintained using properties. Whenever you want to instantiate an object and set data to it's member variables using property you can check some conditions whether the value will be set to the member variable or not. You can restrict read write to a property so that the value of member variable can be readonly, writeonly while accessing the object of that class.
Here's a common pattern:
In short, this allows us to access the Bar object on our instance of Foo. This encapsulation means we don't have to worry about how Bar is retrieved, or if foo.bar has already been instantiated. We can just use the object and let the internals of the Foo class take care of it.
Lots of reasons:
That's the way to use it, except for the way you're setting it, possibly. Instead of accessing the member variable, you may want to use the property from within the class, so you can use uniform rules regarding each member variable. This is the primary advantage to using properties, is to bring the access and setter logic all into one place. It really depends on your specific needs whether or not you want to set it using the Property or not. Note though, that in the constructor you want to be very careful when calling the Property, as you may or may not be relying on other parts of the class being initialized which would not be done yet if accessed through the constructor. Again, this depends on your specific implementation.
It is also a little cleaner to use:
Than what you see in some other languages:
Here's a case where you can encapsulate some logic:
Another way they're useful would be like this:
And now you've got an auto-implemented property with backing member variable that can only be set inside the class but read everywhere else.
Finally, if you need to control the logic, you can write this: