1

Most of my programming assignments have been just simply making subclasses that tie into the base classes. However, as we progress, the emphasis on using get & set methods increases drastically. I just want someone to explain to me what these are, and how they are used in the simplest terms you possibly can. Thank you so much!

Zach
  • 41
  • 1
  • 5
  • 1
    you dont need get/set methods in c# . You have `Properties` to mimic that in a more elegant way. – Vishnu Prasad V Feb 16 '16 at 04:30
  • Though I have a feeling that this question will be closed, I wonder if what you mean by "get & set methods" are actually get and set on properties? I don't recall ever having to use an actual get or set method in C#... – Tyress Feb 16 '16 at 05:55

1 Answers1

5

Get and Set methods in C# are an evolutionary carry over from C++ and C, but have since been replaced by a syntatic sugar called properties

The main point is that you have a variable, or a field, that you want its value to be public, but you don't want the other users to be able to change its value.

Imagine you had this code:

public class Date
{
    public int Day;
    public int Month;
    public int Year;
}

As it stands right now, someone can set Day to -42, and clearly this is a invalid date. So what if we had something to prevent them from doing that?

Now we create set and get methods to regulate what goes in and what goes out, transforming the code into this:

public class Date
{
    // Private backing fields
    private int day;
    private int month;
    private int year;

    // Return the respective values of the backing fields
    public int GetDay()   => day;
    public int GetMonth() => month;
    public int GetYear()  => year;

    public void SetDay(int day)
    {
        if (day < 32 && day > 0) this.day = day;
    }
    public void SetMonth(int month)
    {
        if (month < 13 && month > 0) this.month = month;
    }
    public void SetYear(int year) => this.year = year;
}

Of course this is an overly simplistic example, but that shows how you can use them. And of course you can do calculations on the getter methods, like so:

public class Person
{
    private string firstName;
    private string lastName;

    public string GetFullName() => $"{firstName} {lastName}";
}

Which will return the first and last name, separated by a space. The way I wrote this is the C# 6 way, called String Interpolation.

However, since this pattern was done so often in C/C++, C# decided to make it easier with properties, which you should definitely look into :)

AustinWBryan
  • 3,249
  • 3
  • 24
  • 42