Saturday, 22 December 2018

What is the difference between constant and read only in c#

What is the difference between constant and read only in c#

Constants are declared at compile time using the const keyword and must be initialized when they are declared
Constants value cannot be changed at runtime.

public class CodeViewClass
    public const int GST18 = 18;

A readonly is similar like a constant behaviour with an unchanging value.
But the main difference is that it can be initialized at runtime in a constructor.

public class CoderSampleClass
    // here readonly fiels is declared and asigned value
    public readonly int GST18 = 18;

    // here readonly fiels is declared
    public readonly int GST28;

    public CoderSampleClass()
        // here initializeing vaule in readonly fiels
        GST28 = 28;

  • The value of constant is evaluated at compile time
  • You must assign value const field at time of declaration
  • In C# Const are by default static.
  • The value is same for all objects and cannot be changes
  • No Memory Allocated Because const value is embedded in IL code itself after compilation.
  • Const variable can not be passed as ref or out parameter


  • The value is evaluated at run time.
  • You can assign value readonly field at the time of declaration
  • The value can be change by initializing in the constructor.
  • Dynamic memory allocated for readonly fields
  • You can pass readonly field as ref or out parameters in the constructor context.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.