-1

What is the advantage of the first solution over the second?

class TestClass
    {
        public int value
        {
            get;
            set;
        }
    }
    static void Main()
    {
        var myTest = new TestClass();
        myTest.value = 3;
        System.Console.WriteLine(myTest.value);
    }
}

vs

class TestClass
    {
        public int value;
    }
    static void Main()
    {
        var myTest = new TestClass();
        myTest.value = 3;
        System.Console.WriteLine(myTest.value);
    }

I've search this question on SO, but the top answer I keep seeing is that so in case you need to change how to set/get (add validation or something), you won't need to go back through your code and add it everywhere the property is used. If you do need to add this validation, couldn't you just change it from example two to example one without any additional changes? My understanding is that even if you want to add some validation to the get/set that you can't use the auto generated way like in my example and would need to change it anyway. If that's the case why even have the get/set?

user3715648
  • 1,498
  • 3
  • 16
  • 25
  • 2
    The answer to this question is all over the internet and in most object oriented programming books. – apxcode Oct 30 '14 at 04:47
  • @rufanov I would like to point out the keyword in my sentence: `most`, which implies not all. – apxcode Oct 30 '14 at 05:03

1 Answers1

-1

Getters and Setters have at least two common uses: the first one is to expose your c/c++ code to a scripting language (eg Lua), and the second is to provide for threadsafe atomic access to possibly non-atomic data types (ie, a place for you to provide your preferred threadsafe mechanic).

Homer
  • 89
  • 2