c-sharp
  1. c-sharp-difference-between-readonly-and-constant-in-c

C# Difference between readonly and Constant

In C#, both the readonly and const keywords are used to declare variables whose values cannot be modified at runtime. While they both have similar functionality, there are some key differences between the two. In this tutorial, we'll discuss the differences between readonly and const in C#.

Syntax

Here's the syntax for declaring a constant and a readonly variable in C#:

const int MyConstant = 100;
readonly int MyReadonly = 200;

Notice that constants are declared using the "const" keyword, while readonly variables are declared using the "readonly" keyword.

Example

Let's say we want to declare a variable called "Pi" that represents the mathematical constant "pi". We want the value of Pi to be the same throughout the application, but we want to be able to initialize it dynamically. Here's how we can achieve this using const and readonly:

public class MyClass {
   public const double Pi1 = 3.14159;
   public readonly double Pi2;
   
   public MyClass(double value) {
      Pi2 = value;
   }
}

In the example above, we declare two variables representing pi, "Pi1" and "Pi2". "Pi1" is declared as a constant with a fixed value of 3.14159, while "Pi2" is declared as a readonly variable whose value can be set using a constructor.

Explanation

The main difference between const and readonly is that constants must be initialized with a value at declaration, and that value cannot be changed at runtime. Readonly variables, on the other hand, can be initialized in the constructor, and their value can be changed at runtime.

Another difference is that constants are implicitly static, while readonly variables are not. This means that you can access a constant without creating an instance of the class, but you must create an instance of the class to access a readonly variable.

Use

Use const when you have a value that will never change throughout the lifetime of your application. Use readonly when you have a value that won't change frequently and can be initialized at runtime.

Important Points

  • Constants are implicitly static, so they can be accessed without an instance of the class.
  • Constants must be initialized at the time of declaration, while readonly variables can be initialized in the constructor.
  • Readonly variables can have their value changed at runtime, while constants cannot.

Summary

Both const and readonly are used to declare variables whose values cannot be changed at runtime. However, the main difference between the two is that constants must be initialized at the time of declaration and cannot have their values changed, while readonly variables can be initialized at runtime and have their values changed. With this knowledge, you can now use const and readonly appropriately in your C# code.

Published on: