Q:

What is the difference between constant and readonly in C#?

0

What is the difference between constant and readonly in C#?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Const is nothing but “constant”, a variable of which the value is constant but at compile time. 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.
 
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.
 
In short, Constant variables are declared and initialized at compile time. The value can’t be changed afterward. Read-only is used only when we want to assign the value at run time.
 

Example

We have a Test Class in which we have two variables, one is read-only and the other is a constant.
class Test
{
    readonly int read = 10;
    const int cons = 10;
    public Test()
    {
        read = 100;
        cons = 100;
    }
    public void Check()
    {
        Console.WriteLine("Read only : {0}", read);
        Console.WriteLine("const : {0}", cons);
    }
}

Here, I was trying to change the value of both the variables in the constructor, but when I try to change the constant, it gives an error to change their value in the block that I have to call at run time.

Finally, remove that line of code from class and call this Check() function like in the following code snippet:

class Program
{
    static void Main(string[] args)
    {
        Test obj = new Test();
        obj.Check();
        Console.ReadLine();
    }
}
class Test
{
    readonly int read = 10;
    const int cons = 10;
    public Test()
    {
        read = 100;
    }
    public void Check()
    {
        Console.WriteLine("Read only : {0}", read);
        Console.WriteLine("const : {0}", cons);
    }
}

 Output:

Read only : 100
const : 10

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Interview Questions and Answers,You Need To Know

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Can we use “this” command within a static meth... >>
<< Explain the features of C#?...