0

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?

nintschger
  • 1,786
  • 5
  • 30
  • 45
  • 1
    That's the exact same thing – Thomas Ayoub Jun 19 '15 at 12:49
  • I suggest you read up on properties in c# https://msdn.microsoft.com/en-us/library/w86s7x04.aspx – Jeremy Jun 19 '15 at 12:51
  • 2
    Some think the former is proper, others think the latter is proper ... – Alex K. Jun 19 '15 at 12:51
  • The second is a syntax error... you forgot the `()`? – leppie Jun 19 '15 at 12:53
  • Second option should not compile at all. – Alex Sikilinda Jun 19 '15 at 12:53
  • Here is a thread explaining the difference and more: http://stackoverflow.com/questions/4948816/getters-setters-and-properties-best-practices-java-vs-c-sharp – Peter Jun 19 '15 at 12:55
  • oh, one more thing: Please refrain from the pseudo Hungarian notation like `btnMyButton`. Just come op with an understandable name that describes the field or property. And it's not common practice to start your property with `get` either. Fieldname `myButton` and propertyName `MyButton` should suffice and is clear for everyone. – Stephen Jun 19 '15 at 12:58
  • @Stephen Okay, thank you. – nintschger Jun 19 '15 at 13:01
  • The way you edited the code now shows two _different things_ you changed the second example from a property to a _method_. Which isn't bad in itself, but it invalidates the existing answers since before they were essentially the same mechanism. – D Stanley Jun 19 '15 at 13:02
  • @DStanley: no they weren't. The second option was syntactically incorrect C#, now it's not – Stephen Jun 19 '15 at 13:04
  • @Stephen All of the answers assumed that the _intent_ was to create a property; that's what my comment was based on. – D Stanley Jun 19 '15 at 13:06

8 Answers8

9

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.

keyboardP
  • 68,824
  • 13
  • 156
  • 205
  • 1
    I would just add we usually don't add the "get" prefix. In C#, it's properties, not methods. we access to them withouth "()". for ex. MyClass.MyButton and not MyClass.GetMyButton() – Demonia Jun 19 '15 at 12:59
  • Very good point Demonia, I missed that and just copied the original name, thanks! I've updated the answer. – keyboardP Jun 19 '15 at 13:00
  • @Demonia Thank you. Was learning Java the last weeks and, if I'm not wrong, in Java I was told to use the get and set prefix. – nintschger Jun 19 '15 at 13:04
  • @keyboardP, thats true, in java, we don't have this kind of syntctic sugar and the best practice is to use getter and setter methods. In C# they introduced getter and setter as "properties" then we don't need to declare a variable but we can put some code logic in it. you only need to use method if you want a custom data type (for example another object type, but in this case, it's not really a setter/getter. – Demonia Jun 19 '15 at 13:12
  • @RagnarLodbrok I'd advise that you only add get and set prefixes if the code has to do some significant work, such as accessing a physical device, file, stream, etc. There's no syntactic need to add them (just like adding superfluous type information to variable names) and you code will look cleaner and be more maintainable if you leave them off. – Evil Dog Pie Jun 19 '15 at 13:17
2

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)

Noel Widmer
  • 4,444
  • 9
  • 45
  • 69
1

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.

Evil Dog Pie
  • 2,300
  • 2
  • 23
  • 46
0

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.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
0

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)

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
0

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++)

Steve J
  • 35
  • 1
  • 4
0

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.

Dmitriy Dokshin
  • 710
  • 5
  • 25
0

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;
    }
}