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?
As Thomas mentioned, those are the same things. You may wonder what the point of
getter
andsetter
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 doThe
private set;
ensures only the class can set its value so it's essentially read-only to outside classes. Removing theprivate
will allow external classes to write to the variable too.