C# Keywords Tutorial Part 75: set

C# Keywords Tutorial Part 75: set

C# is an object-oriented programming language that offers a variety of features to enhance the development process. One such feature is the “set” keyword. In this blog post, we’ll explore what the “set” keyword is, how it works, and some code examples.

What is the “set” keyword?

The “set” keyword is used in C# to define a setter method for a property. A setter method is used to assign a new value to a property. In other words, when you use the “set” keyword, you’re defining a method that will be called when you assign a value to a property.

How does it work?

When you use the “set” keyword, you’re defining a method that will be called when you assign a value to a property. Here’s the basic syntax for defining a setter method:

public int MyProperty {
   set {
      // code to assign a new value to MyProperty
   }
}

In this example, we’re defining a setter method for a property called “MyProperty”. The “set” keyword indicates that this is a setter method. Inside the method, we can write code to assign a new value to the property.

Here’s an example of how we can use this setter method:

MyClass obj = new MyClass();
obj.MyProperty = 42;

In this example, we’re creating a new instance of a class called “MyClass”. We’re then assigning a value of 42 to the “MyProperty” property using the setter method we defined earlier.

Code Examples:

Here are some code examples that demonstrate how to use the “set” keyword in C#:

Example 1: Setting a Simple Property

public class MyClass {
   private int myProperty;
   
   public int MyProperty {
      get {
         return myProperty;
      }
      set {
         myProperty = value;
      }
   }
}

// Usage:
MyClass obj = new MyClass();
obj.MyProperty = 42;
Console.WriteLine(obj.MyProperty); // Output: 42

In this example, we’re defining a class called “MyClass” with a private field called “myProperty” and a public property called “MyProperty”. The “set” method assigns a new value to the “myProperty” field.

Example 2: Setting a Readonly Property

public class MyClass {
   private readonly int myProperty;
   
   public MyClass(int value) {
      myProperty = value;
   }
   
   public int MyProperty {
      get {
         return myProperty;
      }
   }
}

// Usage:
MyClass obj = new MyClass(42);
Console.WriteLine(obj.MyProperty); // Output: 42

In this example, we’re defining a class called “MyClass” with a readonly field called “myProperty” and a public property called “MyProperty”. Since “myProperty” is readonly, we can only assign a value to it in the constructor.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *