Friday 3 June 2016

Const and ReadOnly in c#. Difference between const and readonly keyword?



const:-

const is a keyword which is used as a modifier.
Constants (const) are immutable values which are known at compile time and do not change for the life of program.
C# does not support const method, property and events.

Example:-

public const int num=10;
public const string strTest="Welcome";

If you didn’t initialized a constant at the time of declaration then it will show an error.

Ex:-
public const int num;


ReadOnly :-
ReadOnly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.
Example:-
public readonly int num;
you can assign a value to a readonly field only in the following context:-
1.)  At the time of declaration, we can initialized the value
public readonly int num=20;
2.)  In a constructor
public class TestClass1
    {
      
        public readonly int num;
        public TestClass1()
        {
            num = 20;
        }
    }

If you initialized the readonly field value other than over two context then it will give error.
Ex:-
public class TestClass1
    {
      
        public readonly int num;
        public void TestMethod()
        {
            num=20;
        }
    }

 


Note:- Article details referenced by MSDN.
 

No comments:

Post a Comment

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