Search code examples
c#classvariablespublic

The purpose of { get; set}


I'm learning c#. I was wondering, why is

public class Example {

public int X { get; set}

}

used, when you could just use

public class Example {

public int X;

}

Both do the same thing (in my understanding). Both allow you to change the value of the variable. Why use get/set over just declaring the variable public?


Solution

  • The purpose of getters and setters is to do some calculation, processing or update when changing or accessing a property.

    Declaring getters and settters as empty is the same as declaring a public field.

    class Property { 
    
        private bool enabled = false;
        private int numberOfEnabledReadings = 0;
        public bool Enabled {
            get
            {
                //Do some processing (in this case counting the number of accecess)
                numberOfEnabledReadings++;
                return enabled;
            }
            set
            {
                enabled = value;
                //Update GUI
            }
        }
    
    }
    

    edit:

    As I said before: "Declaring getters and settters as empty is the same as declaring a public field.".

    Well, this is true in terms of functionality.

    In fact they are not the same, as mentioned before DataBinding is implemented uppon Properties.

    And, properties take a little overhead, try this:

    class PropertyTest
    {
        public int field = 0;
        public int Property { get; set; }
    }
        private void PropertyChangeTime()
        {
            int counter = 0;
            var instance = new PropertyTest();
            var watch = System.Diagnostics.Stopwatch.StartNew();
            for (int i = 0; i < 100000000; i++)
            {
                instance.field = counter++;
            }
            watch.Stop();
            var elapsedMsField = watch.ElapsedMilliseconds;
            counter = 0;
            watch.Reset();
            watch.Start();
            for (int i = 0; i < 100000000; i++)
            {
                instance.Property = counter++;
            }
            watch.Stop();
            var elapsedMsProperty = watch.ElapsedMilliseconds;
            Console.WriteLine($"field: {elapsedMsField}\nproperty: {elapsedMsProperty}");
        }
    

    In my machine:

    field: 55
    property: 68