Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to use get and set?

I have a code segment:

public class MyClass
{
    private string _myProperty;

    public string MyProperty
    {
        get
        {
            return _myProperty;
        }

        set
        {
            _myProperty = value;
        }
    }
}

What is the point here? I could have declared the _myProperty string as public and any of my class objects will be able to directly access them and get or set the value.

Instead, we are making _myProperty private and the using get and set to access them, using the class object.

In either case, the class object is able to access them and the result is always same.

So why use this approach? Is that only because I can implement few constraints in setter?

Apart from that what harm will making member variables public cause? In this example I could expose _myProperty as public instead of restricting it to this class only by making it private, as OOP would suggest.

like image 528
Simsons Avatar asked Nov 01 '11 14:11

Simsons


1 Answers

No, the result isn't always the same.

  • Try binding to a public field (or doing anything else which uses reflection and expects properties)
  • Try passing a property by reference (you can't)
  • Try later deciding you want logging etc and finding that when you change it to a property, you lose both source and binary compatibility.

Read the article I wrote on this a while ago...

Note that as of C# 2 your code can be a lot shorter though:

public class MyClass
{
    public string MyProperty { get; set; }
}
like image 158
Jon Skeet Avatar answered Oct 20 '22 23:10

Jon Skeet