Constants
- Constants are static by default.
- They must have a value at compilation-time (you can have e.g. 3.14 * 2 + 5, but cannot call methods).
- Could be declared within functions.
- These are copied into every assembly that uses them (every assembly gets a local copy of values).
- using System;
- namespace ConstantExample
- {
- class ConstantExample
- {
- private const int PI = 3.14;
- public static void Main()
- {
- //You have to initialize Const variables while declaration
- const int RollNo = 1284;
- //Valid scenario
- const int Age = 10 + 13;
- const string Name = "Satish Kumar";
- // Reassigning a const variable is not allowed.
- RollNo = 1405; // Will result compile time error.
- Age++; // Will result compile time error.
- Console.WriteLine(Name);
- Console.Read();
- }
- }
- }
Readonly
- Must have set value, by the time constructor exits.
- Are evaluated when instance is created.
- 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.
- using System;
- namespace ReadOnlyExample
- {
- class ReadOnlyTest
- {
- //You have to initilize readonly varabiles while declaration or in constructor
- readonly int RollNo = 1284;
- //Valid scenario
- readonly int Age;
- readonly string Name = "Satish Kumar";
- //readonly fields can be initlized in constructor
- public ReadOnlyTest (string name)
- {
- Age = 23;
- Name = name;
- }
- public changeName(string newName)
- {
- Name = "Satish Kumar Vadlavalli"; ; // Will result error.
- }
- }
- class ReadOnlyExample
- {
- public static void Main()
- {
- ReadOnlyTest obj = new ReadOnlyTest("Satish");
- Console.Read();
- }
- }
- }
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.
A blog without comments is not a blog at all, but do try to stay on topic. Please comment if you have any questions or leave your valuable feedback. Happy Learning.

Md HussainPosted Oct 29, 2020, 11:37 AM
Good explanation
paritosh MishraPosted Aug 14, 2019, 1:31 PM
Nice explanation
Lalit RaghavPosted Jun 4, 2018, 1:24 AM
Nice explanation
SubashPosted Sep 8, 2016, 8:52 AM
Nice