Home  >  Article  >  Backend Development  >  Final local variables in C#

Final local variables in C#

WBOY
WBOYforward
2023-09-12 15:05:021408browse

C# 中的最终局部变量

To make a local variable final, use the read-only keyword in C# because it is not possible to implement the final keyword.

The read-only keyword allows a variable to be assigned only once. Fields marked "read-only" can only be set once during object construction and cannot be changed.

Let's look at an example. Below, we set the empCount field to be read-only and cannot be changed once assigned.

Example

class Department {
   readonly int empCount;

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

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

The above is the detailed content of Final local variables in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete