top of page

What is Difference Between Const, ReadOnly in C#

Updated: Jun 23, 2019


Constant

Const is nothing but "constant", a variable of which the value is constant but at compile time. And it's mandatory to assign a value to it. By default a const is static and we cannot change the value of a const variable throughout the entire program.

  • In C#, constant fields are created using const keyword.

  • The value of the const field can not be changed.

  • In const fields, we can only assign values in declaration part.

  • It cannot be used with static modifiers.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;

namespace ConsoleApp1 { class Program { public const int myvar = 10; public const string str = "CodersArts";

// Main method static public void Main() {

// Display the value of Constant fields Console.WriteLine("The value of myvar: {0}", myvar); Console.WriteLine("The value of str: {0}", str); Console.ReadKey(); } } }

Output of Program:


Read Only

Readonly is the keyword whose value we can change during runtime or we can assign it at run time but only through the non-static constructor. Not even a method.

  • In C#, readonly fields can be created using readonly keyword

  • ReadOnly is a runtime constant.

  • ReadOnly is a runtime constant.

  • It can be used with static modifiers.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;

namespace ConsoleApp1 { class Program { public readonly int value1; public readonly int value2;

// Values of the readonly // variables are assigned // Using constructor public Program(int b, int c) {

value1 = b; value2 = c; Console.WriteLine("Display value of value1{0}, " + "and value2{1}", value1, value2); }

// Main method static public void Main() { Program obj1 = new Program(100, 200); } }

}

Output of Program:


Output

For more details contact click here

If you like Codersarts blog and looking for Assignment help,Project help, Programming tutors help and suggestion you can send mail at contact@codersarts.com.

Please write your suggestion in comment section below if you find anything incorrect in this blog post.

bottom of page