Final local variables in C#

CsharpProgrammingServer Side Programming

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
   }
}
raja
Published on 14-Aug-2018 08:07:49
Advertisements