Readonly and Constant members in C# with Example

By
1.) Read-only Field:-
The readonly keyword is  a modifier that you can use 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 construction in the same class.You can learn constructor concepts more details.
You can assign a value to a readonly field only in the following way.
  • Variable can be initialized at declaration time.
           Ex. Public readonly int p=8;
  • For an instance field ,in the instance constructors of the class that contains the field declaration.
                                                                              OR
  • For a static field ,in the static constructor of the class that contains the field declaration .
  • You can also pass a readonly field as an out or ref parameter.
Example:-
using System;
namespace Read_onlyConsle
{
    public class ReadOnly
    {
        class MyClass
        {
            public int x;
            public readonly int y = 5; // Initialize a readonly field
            public readonly int z;

            public MyClass()
            {
                z = 4;   // Initialize a readonly instance field
            }

            public MyClass(int a1, int a2, int a3)
            {
                x = a1;
                y = a2;
                z = a3;
            }
        }
        public static void Main()
        {
            MyClass p1 = new MyClass(110, 120, 230);   
            Console.WriteLine("For p1 object: x={0}, y={1}, z={2}", p1.x, p1.y, p1.z);
            MyClass p2 = new MyClass();
            p2.x = 44;
            Console.WriteLine("For p2 object: x={0}, y={1}, z={2}", p2.x, p2.y, p2.z);
            Console.ReadKey();
        }
    }
    }

OUTPUT
Description:-
  • In above code ,we have taken two readonly members y,z ,but here x is a simple member. We have initialized readonly members (y=25, z=24).but x is declared as integer type.
  • we have used two constructors.One takes zero argument and second takes three arguments.
  • When we create the object of myclass p1, and pass some values at that time.you will see following output in above snapshot.
          For P1 object: x=110,y=130,z=230
  •  you can see, values of y and z will be changed at runtime.
  • Now again , we have created object of myclass p2 .so that we can easily understand.After that initialized some value in variable x,you already know ,x is a simple variables. p2.x=44; if you want to initialize  p2.y=15; p2.z=10 then it will show compile time error.Means you can't initialize readonly variables at run time.
Note:-
  • The Read only field can be initialized either at declaration or in a constructor.Therefore,readonly field can have different values depending on the constructor used.
  • A const field is a compile -time constant ,the readonly can be used for runtime constant as given below.
         Public static readonly uint A=(uint) Datetime.Now.Ticks; .

2.) Constant Field :-
The const keyword is used to modify a declaration of a field or local variable. It specifies that the value of the field or the local variable cannot be modified. A constant declaration introduces one or more constants of a given type. 
Constant Declaration Syntax

[attribute ][modifier] const [type][declarators];
Example:-
public const int x=56;

Note:-
  • Attribute and Modifier is optional.
  • Type can be byte, char, short, int, long, float, double, decimal, bool, string, an enum type, or a reference type. 
  • The attributes and modifiers apply to all of the members declared by the constant declaration.
  • The type of a constant declaration specifies the type of the members introduced by the declaration. A constant expression must yield a value of the target type, or of a type that can be implicitly converted to the target type. 
  • A constant expression is an expression that can be fully evaluated at compile time. Therefore, the only possible values for constants of reference types are string and null.
  • We can declare multiple constants in one line as given below:-
          public const int a=8;b=9;c=5; d=7;
  • The static modifier is not allowed in a constant declaration.
  • A constant can participate in a constant expression as given below:-
          public const int a=8;
    public const int b=7;
    public const int c=a+b+45;
Example of Constant:-

using System;
namespace Constant_console
{
    public class Constant
    {
        class MyClass
        {
            public int x;
            public int y;
            public const int a1 = 25;
            public const int a2 = a1 + 5;

            public MyClass(int p1, int p2)
            {
                x = p1;
                y = p2;
            }
        }
        public static void Main()
        {
            MyClass obj = new MyClass(110, 220);
            Console.WriteLine("x = {0}, y = {1}", obj.x, obj.y);
            Console.WriteLine("a1 = {0}, a2 = {1}", MyClass.a1, MyClass.a2);
            //use constant as a local variable...
            const int a = 400;
            Console.WriteLine("My local constant = {0}", a);
            Console.ReadKey();
        }
    }
}

OUTPUT:-

Difference between Readonly and Constant Fields:-
The readonly keyword is different from the const keyword.
  • A const field can only be initialized at the declaration of the field. 
  • A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used.
  •  A const field is a compile-time constant.
  • The readonly field can be used for runtime constants as in following.
    Public static readonly uint A=(uint) Datetime.Now.Ticks;
For More...

0 comments:

Post a comment

Powered by Blogger.