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

Final variables in C#

WBOY
WBOYforward
2023-09-06 22:41:12725browse

C# 中的最终变量

Java has the final keyword, but C# does not have its implementation. The same implementation is achieved in C# using seal or readonly keyword.

readonly allows a variable to be assigned a value only once. Fields marked "read-only" can only be set once during object construction. It cannot be changed.

Example

class Employee {
   readonly int age;

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

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

Above, we set the age field to read-only and cannot be changed once assigned.

The above is the detailed content of Final 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