call a getter on an instance of a class in csharp

In C#, a getter is a type of accessor that allows you to retrieve the value of a private field in your class from an instance of the class. Here's an example of how to call a getter on an instance of a class:

main.cs
public class MyClass {
   private int myData;

   public int MyData {
      get { return myData; }
      set { myData = value; }
   }
}

class Program {
   static void Main(string[] args) {
      MyClass myInstance = new MyClass();
      myInstance.MyData = 42; // calls the setter
      int result = myInstance.MyData; // calls the getter
      Console.WriteLine(result); // prints "42" to the console
   }
}
410 chars
18 lines

In the above example, we define a simple class called MyClass which has a private field myData and a public property MyData. The MyData property has both a getter and a setter, which allow us to get and set the value of the private myData field.

To call the getter on an instance of MyClass, we simply read the value of the MyData property. In the example above, we create a new instance of MyClass and assign the value 42 to its MyData property using the setter. We then call the getter on the same instance and assign the returned result to the result variable. Finally, we print the value of result to the console, which outputs "42".

gistlibby LogSnag