Saturday, 9 January 2016

C#.NET Readonly

A readonly field can be initialized either at the declaration or in a constructor.

Example Program for C#.NET read only

Program

using System;

namespace ReadOnly
{
    class Program
    {
        static void Main(string[] args)
        {
            Maths m = new Maths();

            Console.ReadKey();
        }
    }

    class Maths
    {
        const int a = 10;
        readonly int b = 20;

        public Maths()
        {
            b = 25; //Assigning value to ready only variable in constructor
            // a = 20; //Value cannot be assigned to Const variable
            Console.WriteLine(b);
        }
    }
}

Output
25

No comments:

Post a Comment