Final local variables in C#


To set final for a local variable, use the read-only keyword in C#, since the implementation of the final keyword is not possible.

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.

Let us see an example. Below, we have set the empCount field as read-only, which once assigned cannot be changed.

Example

class Department {
   readonly int empCount;

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

   void ChangeCount() {
      //empCount = 150; // Compile error
   }
}

Updated on: 21-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements