What is difference between readonly and const in C#? – Programming, Pseudocode Example, C# Programming Example
C#

What is difference between readonly and const in C#?

const in C#

  • You have to initialize const variables while declaration.
  • You cannot reassign a const variable.
  • Compiler evaluates the const variables.
  • The static modifier is not allowed in a constant declaration.
  • A const field of a reference type other than string can only be initialized with null.

Example for const in c#.net

readonly in C#

  • readonly fields can be initialized only while declaration or in the constructor.
  • Once  you initialize a readonly field, you cannot reassign it.
  • You can use static modifier for readonly fields
  • readonly modifier can be used with reference types
  • readonly modifier can be used only for instance or static fields, you cannot use readonly keyword for variables in the methods.

Example for readonly modifier in c#.net

Difference between const and readonly

  • const fields has to be initialized while declaration only, while readonly fields can be initialized at declaration or in the constructor.
  • const variables can declared in methods ,while readonly fields cannot be declared in methods.
  • const fields cannot be used with static modifier, while readonly fields can be used with static modifier.
  • A const field is a compile-time constant, the readonly field can be used for run time constants.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.