0

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?

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
jack.py
  • 362
  • 8
  • 23
  • What if you want to dynamically calculate the value? For example, an `Area` property on a `Shape` object which calculates the area based on the dimensions of the shape. Or what if you want to trigger something inside the object when the value is set? A directly exposed class variable can't do these things. Objects should expose behaviors, not values. Getting/setting backing values is a behavior. Code outside the object has no business knowing how that value is stored, what else it's used for, etc. – David Jan 25 '20 at 02:50
  • In object oriented programming both are "anti-pattern". Instead expose(make public) only methods which do something with the values stored privately in the object. – Fabio Jan 25 '20 at 02:54
  • 2
    @Fabio whuuut; I think you're in the wrong tag. Try typing `[java]` in the search box? :) – Caius Jard Jan 25 '20 at 03:05
  • Duplicate of [What is the purpose of get : set?](https://stackoverflow.com/questions/18966091/what-is-the-purpose-of-get-set) See Also all [9,370,000 alternatives](https://www.google.com/search?rlz=1C1CHFX_enUS460US460&biw=1163&bih=778&ei=M7ErXse6Ctq0tQaixbNA&q=%7B+get%3B+set%7D+c%23+site%3Astackoverflow.com&oq=%7B+get%3B+set%7D+c%23+site%3Astackoverflow.com&gs_l=psy-ab.3...8781.8781..9076...0.1..0.103.103.0j1......0....1..gws-wiz.......0i71.RlMKGFlSarU&ved=0ahUKEwiHoOyE453nAhVaWs0KHaLiDAgQ4dUDCAs&uact=5) and similar posts here – Ňɏssa Pøngjǣrdenlarp Jan 25 '20 at 03:08
  • @Fabio: Getters and setters *are* methods. The syntax used is mostly for convenience, but they compile down to the same method structure you're talking about from Java. – David Jan 25 '20 at 11:54

2 Answers2

3

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
  • Don't forget that setters and getters can also be assigned more restrictive access modifiers than their enclosing property. Also, declaring an empty property is not the same as declaring a field (Don't worry I just found out myself :p). Take a look at the link Caius Jard posted in the comments. – Jesse Jan 25 '20 at 03:11
  • This is correct. Strictly "they are not the same". –  Jan 25 '20 at 03:22
1

take a look at the following sources

https://www.w3schools.com/cs/cs_properties.asp

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties

basically properties allow you to specify how your class' objects are able to manipulate and/or access their private variables.