9

I've been learning C# for a while now, and I've come across properties in my C# book (Head First C#). I honestly do not understand what they're used for, and why I should use them. I've googled them a few times but still cannot for the life of me understand them.

Can someone please explain to me this foreign concept?

Thanks,

Varmitharen

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Varmitharen
  • 93
  • 1
  • 3
  • 1
    Foreign *compared to what*? What are you currently using? public fields? – Marc Gravell Jun 25 '11 at 08:54
  • 2
    yeah, don't do that ;p Public fields is almost never a good idea. – Marc Gravell Jun 25 '11 at 10:38
  • Public fields are generally not good practice, but if your class is only being used internally and is a self-contained application, forcing a recompile may not actually matter. That being said, in .Net 3.5 and higher you can replace Public fields with public properties very easily by just adding `{ get; set;}` . E.g., replace `int foo;` with `int foo {get; set;}` . Of course, if your implementation types are logically different than your exposed properties, using a field will make your code more painful to use. – Brian Jun 29 '11 at 21:36
  • have look to this link [Properties (C# Programming Guide)](http://msdn.microsoft.com/en-us/library/x9fsa0sw.aspx) also this one [Why we need Properties in C#](https://stackoverflow.com/questions/1523548/why-we-need-properties-in-c) – DeveloperX Jun 25 '11 at 08:49

4 Answers4

19

Properties provide controlled access to data; at the most basic, it can just mean encapsulating a field (public fields are not recommended), which the compiler can make easy for you:

public int Foo {get;set;} // the compiler handles the field for you

You could, however, use the property to enforce logic or handle side effects:

private int foo;
public int Foo {
    get { return foo; }
    set {
        if(value < 0) throw new ArgumentOutOfRangeException();
        if(value != foo) {
            foo = value;
            OnFooChanged(); // fire event notification for UI bindings
        }
    }
}

Other common options are lazy-loading, calculated members, proxied members, etc.

You can also change the accessibility, for example:

public int Foo { get; protected set; }

which can only be assigned by the type and subclasses, not by unrelated code. It could also only have a get or set.

Basically, properties act as a more formal version of a get/set pair of methods, making it much easier to talk about "Foo", rather than "get_Foo"/"set_Foo" etc (for two-way binding).

Unlike fields, properties can also be advertised on interfaces, which is essential for interface-based code

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Another reason for even basic compiler generated properties over fields is that it gives you flexibility later on when reimplementing the logic of the getter and setter if need be without recompiling consuming code. If you publish fields and then decide you want to enforce setter logic, you've got to make the field private, implement a property and then everyone consuming your code has to recompile. – jasonh Jun 25 '11 at 17:57
19

Though the other answers are pretty good, they are all very much about the mechanism of properties. It is also helpful to understand the philosophy of properties.

In OO programming we spend a lot of time building models of semantic domains. When you say that you have a class "Animal" and a derived class "Tiger", you're modeling in the computer realm a fact about the real world: that of all things in the world, some of them are animals, and of those animals, some of them are tigers.

But you have to understand that the mechanism and the semantics are different. No one says "hey, let's go to the zoo and watch the instances of zookeeper invoke methods on IFeedable on the instances of the tigers".

A field is a mechanism and therefore should be a private implementation detail of a class; it does not describe part of the model. A property is a part of the semantic model. Every tiger has a birthday, so "Birthday" should be a property of the Tiger class. That's part of the "semantic model" of tigers, so expose it as a property. As an implementation detail, the birthday might be stored in a private field accessed by the property.

Does that make sense? In short: use public properties to describe the semantic properties of the things you are modeling; use private fields as implementation mechanisms.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
4

Properties are used to enrich the Encapsulation concept of Object-Oriented Programming.

i.e. They encapsulate a field-member and let you (the developer) control how setting/getting this variable is done. Example?

public class Person
{
    private int m_age;

    public int Age
    {
        set
        {
            if(value < 18)
                m_age = 18;
            else
                m_age = value;
        }
        get
        {
            return m_age;
        }
    }
}

See? using property Age, we guaranteed that the minimum set value of age is 18.

Ken D
  • 5,880
  • 2
  • 36
  • 58
  • They DO NOT necessarily encapsulate a field member. – jason Jun 27 '11 at 00:32
  • And even when they do encapsulate a field member, the field member is not necessarily the same type as the property. I don't like this example that much; I generally prefer that properties that have both a `get` and a `set` have the `get` return the value that was `set`. – Brian Jun 29 '11 at 19:28
  • @Brian, this is determined according to the developer's needs and the case at hand, and sometimes we may put what we "like" aside in favor of what is "better". On the other hand, from the way this question was asked, I deducted that the OP needs a simple example to grasp the idea of Properties, that's why my answer was the author's accepted not the community's accepted. The other answers are very good though. – Ken D Jun 29 '11 at 21:14
1

Are you familiar with fields, then? If so, from the point of view of code that consumes your class, properties are exactly like fields. Inside your class though, a property is like a pair of methods, one that deals with returning the value to the consumer, and one method that deals with updating the value. These methods are generally called getters and setters.

A good reason for wanting to use a property instead of a field is that it gives you better control of the values passing in and out of the property.

Peter Lillevold
  • 33,668
  • 7
  • 97
  • 131