Final variables in C#


Java has a final keyword, but C# does not have its implementation. Use the sealed or readonly keyword in C# for the same implementation.

The readonly would allow the variables to be assigned a value only once. A field marked "read-only", can only be set once during the construction of an object. It cannot be changed.

Example

class Employee {
   readonly int age;

   Employee(int age) {
      this.age = age;
   }

   void ChangeAge() {
         //age = 27; // Compile error
   }
}

Above, we have set the age field as readonly, which once assigned cannot be changed.

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 21-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements