Posted by : Sudhir Chekuri Saturday, 9 January 2016

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

Leave a Reply

Subscribe to Posts | Subscribe to Comments

Followers

Total Pageviews

Powered by Blogger.

- Copyright © 2013 DevStudent - Metrominimalist - Powered by Blogger - Designed by Johanes Djogan -