How do I call a getter or setter in C#

c#, c#-4.0

Solution

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.

Problem

I understand how to create a getters and setters ``` public myClass { public int myVal { get; set; } // more stuff } ``` but I don't understand how to call it later on. ``` public myOtherClass { public myOtherClass() { myClass localMyClass = new myClass(); localMyClass.???set??? = 42; // Intelisense doesn't seem to give any obvious options after I enter // the period. } } ``` How should I set the value of myVal in localMyClass?

Original source

Related problems