0

What is the difference between the implementation of

Class cl1
{
    public int var{get;set;}
}

and

Class cl1
{
    public int var;
}

I mean, both are implemented like this -

void Main()
{
    cl1 obj = new cl1();
    obj.var = 25;
    int k = obj.var;
}

and if there is no difference, then why do I see the 2nd implementation so common in Library Assemblies??

1 Answers1

0

I think about two reason:

  1. it hide the implementation: property var may use a private field which isn't a var or may not use a private field at all and the client will not know this

  2. It's easier to change: if in your code you use field obj.var 100 times and at some point you must change something of that field you have to modify all the calls, while if you have a property you can modify the implementation in a simpler way without having to modify all the call (at least if you don't change the signature of the property)

probably other reason that doesn't come to my mind now

Fabio Marcolini
  • 2,315
  • 2
  • 24
  • 30