18

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;
}
Gavin Miller
  • 43,168
  • 21
  • 122
  • 188
peter
  • 8,158
  • 21
  • 66
  • 119
  • possible duplicate of [Should I use public properties and private fields or public fields for data?](http://stackoverflow.com/questions/1277572/should-i-use-public-properties-and-private-fields-or-public-fields-for-data) – nawfal Jul 17 '14 at 20:21
  • 1
    They're useful for data binding. – recursive Oct 06 '09 at 04:09

8 Answers8

36

Short answer: Encapsulation

Long answer: Properties are very versitile. It allows you to choose how you want to expose your data to outside objects. You can inject some amount of data validation when setting values. It also aliviates the headache of getX() and setX() methods seen in the likes of Java, etc.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • 14
    Short Answer: to make the getX()/setX() pattern prettier. Long answer: Encapsulation. [citation needed] ;) – Jimmy Oct 06 '09 at 04:11
  • 1
    e.g. see http://stackoverflow.com/questions/1461598/what-is-the-point-of-setters-and-getters-in-java – Jimmy Oct 06 '09 at 04:12
  • +1 for answer -1 for question: Why this answer is not accepted? – Navid Rahmani Jun 25 '11 at 08:52
  • what? ...headache of getX and setX... - omg, you just miss the BIG easiness of grouping all available setters together... THE BIG drawback of properties. – Bernhard Mar 16 '17 at 09:25
  • but when people write string value {get;set;} , how is it different from initialising fields directly? – judy Dec 06 '22 at 01:39
27

Think about it: You have a room for which you want to regulate who can come in to keep the internal consistency and security of that room as you would not want anyone to come in and mess it up and leave it like nothing happened. So that room would be your instantiated class and properties would be the doors people come use to get into the room. You make proper checks in the setters and getters of your properties to make sure any unexpected things come in and leave.

More technical answer would be encapsulation and you can check this answer to get more information on that: https://stackoverflow.com/a/1523556/44852

class Room {
   public string sectionOne;
   public string sectionTwo;
}

Room r = new Room();
r.sectionOne = "enter";

People is getting in to sectionOne pretty easily, there wasn't any checking.

class Room 
{
   private string sectionOne;
   private string sectionTwo;
   
   public string SectionOne 
   {
      get 
      {
        return sectionOne; 
      }
      set 
      { 
        sectionOne = Check(value); 
      }
   }
}

Room r = new Room();
r.SectionOne = "enter";

now you checked the person and know about whether he has something evil with him.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Tarik
  • 79,711
  • 83
  • 236
  • 349
20

Lots of reasons:

  • Semantics. Properties separate the implementation of your type from the interface.
  • Binary Compatibility. If you ever need to change a property, you can do so without breaking binary compatibility for dependent code. With fields, you have to recompile everything even if the new implementation uses a property with the same name.
  • Databinding. You can't databind to a field.
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • *Bitch slap myself* I didn't know that Binary Compatibility thing. Nice. – Tarik Oct 06 '09 at 04:23
  • @Justin: only on days that end in 'y', but sometimes not for very long. – Joel Coehoorn Oct 06 '09 at 04:24
  • @Joel: I know the feeling. That time seems to grow less and less day by day. – Justin Niessner Oct 06 '09 at 04:30
  • @JoelCoehoorn can you elaborate a bit more on the binary compatibility or maybe guide to a resource that explains the difference between field and properties regarding binary compatibility? – Bongo Dec 16 '20 at 09:32
  • @Bongo did you ever get to the bottom of binary compatibility question, I am not too clear either, I thought to check, whether you received any answer. – Vivek Shukla Jun 21 '21 at 00:42
9

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"

Akash Kava
  • 39,066
  • 20
  • 121
  • 167
7

Here's a common pattern:

class Foo {

    private Bar _bar;

    //here, Foo has a Bar object.  If that object has already been instantiated, return that value.  Otherwise, get it from the database.
    public Bar bar {
        set { _bar = value;}
        get {
            if (_bar == null) {
                _bar = Bar.find_by_foo_name(this._name);
            }
            return _bar;
        }
    }
}

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.

Doug R
  • 5,749
  • 2
  • 28
  • 32
4

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:

myObject.Property1 = "Test String";
Console.WriteLine(myObject.Property1);

Than what you see in some other languages:

myObject.setProperty1("Test String");
System.out.writeln(myObject.getProperty1());

Here's a case where you can encapsulate some logic:

public int Order
{
    get { return m_order; }
    set
    {
        // Put some rules checking here. Maybe a call to make sure that the order isn't duplicated or some other error based on your business rules.
        m_order = value;
    }
}

Another way they're useful would be like this:

public int Order { get; private set; }

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:

public int Order
{
    get { return m_order; }
    protected set
    {
        // Again, you can do some checking here if you want...
        m_order = value;
        // You can also do other updates if necessary. Perhaps a database update...
    }
}
jasonh
  • 29,297
  • 11
  • 59
  • 61
4

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 and set methods but in real life you may need to do certain things like

  • Store currency in 10th of cents as a long integer but return to the outside world as a string with 2 decimal spaces and a $ sign.
  • Restrict a certain property to be read-only (or even write-only: for ex:, a password validator/hash generator class).
  • Change the state of the object somehow when this value is set/get.

In Java, you write getters and setters which are plain-old methods that return or accept a value respectively.

Chetan S
  • 23,637
  • 2
  • 63
  • 78
  • +1 for the access specifier aspect for regulating not only at data level (like members) but operation level (get/set): read-only, write-only – jdehaan Oct 06 '09 at 04:48
  • At IL level properties are methods as well. In fact the C# compiler create methods like get_Order and set_Order for the property and won't allow you to define your own method with the same names. – softveda Oct 06 '09 at 06:04
4

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.

Himadri
  • 8,600
  • 15
  • 47
  • 70