Getter and Setter in C#

9k views Asked by At

I'm just playing around with C# and I'm aksing myself which the proper method is for Getter and Setter. I found something like this with google:

class MyClass
{
    Button btnMyButton;

    // some code...

    public Button getBtnMyButton
    {
        get
        {
            return btnMyButton;
        }
    }
}

is there a 'proper' way? Or is this also okay:

class MyClass
{
    Button btnMyButton;

    // some code...

    public Button getBtnMyButton()
    {
         return this.btnMyButton;
    }
}

Whats the difference?

8

There are 8 answers

5
keyboardP On BEST ANSWER

As Thomas mentioned, those are the same things. You may wonder what the point of getter and setter is in that case and it's mainly syntactic sugar. However, it also means you don't have to create an explicit field as one is created for you in the background. Therefore, you can simply do

public Button MyButton { get; private set; }

The private set; ensures only the class can set its value so it's essentially read-only to outside classes. Removing the private will allow external classes to write to the variable too.

0
MakePeaceGreatAgain On

Actually a getter/setter is nothing but a method returning/providing the internal value. So while writing

public Button getBtnMyButton
{
    get
    {
        return btnMyButton;
    }
}

you actually write a getter-method similar to this one:

public Button getBtnMyButton
{
     return this.btnMyButton;
}

So the similar way in java is using methods.

0
AudioBubble On

The difference is that:

public Button getBtnMyButton()
{
     return this.btnMyButton;
}

is a method, which can accepts inputs parameters and returns an output parameter.

The other:

public Button getBtnMyButton
{
    get
    {
        return btnMyButton;
    }
}

is a property. You can see a propery as a "wrapper" around a variable, that allow you to validate the variable value and to perform other kind of stuffs.

Example:

public Button getBtnMyButton
{
    get
    {
        if (btnMyButton != null)
            return btnMyButton;

        throw new Exception("Button is null!");
    }
    set
    {
        if (value == null)
            return;

        btnMyButton = value;
    }
}
0
Thomas Ayoub On

That's the same, this call in is implicit.

The shorter you can do is:

class MyClass
{
    // some code...

    public Button getBtnMyButton { get; private set; }
}

And I recommend you a bit of reading : Auto-Implemented Properties (C# Programming Guide)

0
Steve J On

They're basically the same thing. The this pointer refers to the object that is calling the method.

A interesting thing about the this pointer is that it allows you to write set functions like

public void setMyButton (Button myButton)
{
    this.myButton = myButton;
}

(Not sure if that's valid C# because I've never worked with it, but you get the idea. That should work in Java/C++)

0
Noel Widmer On

You usually do not add a get/set prefix to properties. Just write it like that:

private Button myButton;

public Button MyButton{
   get{
      return myButton;
   }
   /*set{
      myButton = value;
   }*/
}

And yes, it means the same in your context. The this. would be required in this scenario:
(Note: This is a stupid example and should only show you the idea)

private Button myButton;

public Button MyButton{
   get{
      Button myButton = null;
      return this.myButton; //<- this. is required or you would end up getting null all the time.
   }
   /*set{
      myButton = value;
   }*/
}

Edit:
Adding get/set comes from languages such as C++ or Java where you do not have the luxury of properties. Using get/set indicates a (heavy) operation. And the developer may think about caching the result instead of calling it numerous times.
Only use get/set on methods where you want to specify a (heavy) operation. You may even end up using properties instead of methods if it is a very (easy) operation. In Intellisense (Visual Studio) a property is presented just like a field and thus we can assume that there is no operation going on. Thus I will (usually) never cache the result of a property.

On the other hand - if I find a property called GetResultOfImposible.
Then I would propably decide to cache that.
A property named ResultOfImposible sounds less heavy and I wouldn't cache it.
(Maybe I would change my mind after finding a performance peak)

0
Evil Dog Pie On

You should think about the naming of the property a little more, because one property can have both a getter and a setter. Consider the following:

public class MyClass
{
    private Button btnMyButton;

    public Button getMyButton
    {
        get{ return btnMyButton; }
        set{ btnMyButton = value; }
    }
}

    // in some other class
    void ChangeActiveButton(Button newButton)
    {
        MyClass theThing = GetTheThing();

        // This doesn't read well...
        theThing.getMyButton = newButton;
    }

When you implement property getters and setters, don't prefix the name with 'get' and set'. (To many developers, the words 'get' and 'set' in a method or function imply that the code has to go off and do some work to complete the getting or setting, rather than simply return or assign a value that is already to hand.)

public class MyClass
{
    private Button btnMyButton;

    // Note that the property just has a name, no prefix.
    public Button MyButton
    {
        get{ return btnMyButton; }
        set{ btnMyButton = value; }
    }
}

Also note that you can make property getters and setters private even though the property itself is exposed outside the class.

public Button MyButton
{
    get{ return btnMyButton; }
    private set{ if(null == btnMyButton) btnMyButton = value; }
}

This provides the MyClass with priveliged access to the setter, which can be used to implement any property-specific assignment rules.

You can also use Auto-Implemented Properties, without the additional member variable.

public Button MyButton { get; private set; }

Properties in c# are great. Use them wisely and it will help you create better structured, more easily maintainable code.

0
Dmitriy Dokshin On

The difference is in purpose. You should use property, when code just returns some value with few logic or without it at all. Also in general the value should be the same, if setter was not called. When the value is created (not stored) or logic is complex, you should use method. It is a good practice to create self-documented code.