Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a getter or setter in C#

Tags:

c#

c#-4.0

People also ask

What do you call getters and setters?

Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.

What is getter in C?

The getter function is used to retrieve the variable value and the setter function is used to set the variable value. Remember: You can directly access public member variables, but private member variables are not accessible. Therefore, we need getter functions.

What are getters and setters in C sharp?

It is a good practice to use the same name for both the property and the private field, but with an uppercase first letter. The get method returns the value of the variable name . The set method assigns a value to the name variable. The value keyword represents the value we assign to the property.


localMyClass.myVal = 42;

Getters and setters let you treat the values like public properties. The difference is, you can do whatever you want inside the functions that do the getting and setting.

Examples:

store other variables

private int _myVal, myOtherVal;
public int MyVal { get; set { _myVal = value; myOtherVal++; } }

make numbers up / return constants

public int MyVal { get { return 99; } set; }

throw away the setter

private int _myVal;
public int MyVal { get { return _myVal; } set { ; } }

In each of these cases, the user will feel like it's just a public data member, and simply type

localMyClass.myVal = 42;
int i = localMyClass.myVal;

The gettors and settors let you make an implementation of your own. Also, as Hogan says, "There are a number of libraries and add-ons [e.g. MVC.NET] that require you to use getter and setter functions" - even if it's for the trivial {get; set;} case.


Set:

localMyClass.myVal = 42

Get:

int variable = localMyClass.myVal;

From the outside, the syntax for accessing getters and setters is indistinguishable from that of accessing variables. Assignments translate into calls of setters, while plain expression uses translate into calls of getters.

In intellisense, the list of getters and setters should open upon placing a dot . after the variable name. Properties should have blue markers to the left of them (as opposed to magenta-colored markers to the left of methods).


You want this

localMyClass.myVal = 42;  

to call the setter

and this

varName = localMyClass.myVal;

to call the getter.