Wednesday 21 September 2016

ReadOnly in CSharp with example


/*

    The 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.


    Difference between Const and ReadOnly in C#.

    const
    They can not be declared as static (they are implicitly static)
    The value of constant is evaluated at compile time
    constants are initialized at declaration only

    readonly
    They can be either instance-level or static
    The value is evaluated at run time
    readonly can be initialized in declaration or by code in the constructor


    more on https://msdn.microsoft.com/en-us/library/acdd6hb7.aspx


*/

using System;

namespace ReadOnly_in_CSharp
{
    public class Program
    {
        private readonly string fixvalue_readonly = "readonly";
        private const string fixvalue_const = "const";

        static string _readonly = "";
        static string _const = "";

        public Program()
        {
            fixvalue_readonly = "_readonlyChanged";
            //fixvalue_const = "_constChangedVlue";
            _readonly = fixvalue_readonly;
            _const = fixvalue_const;
        }


        public void ChangeValue()
        {
            //fixvalue_readonly = "_readvalueChanged2"; //Error A readonly field cannot be assigned to(except in a constructor or a variable initializer)
            //fixvalue_const = "_constvalueChanged2"; //Error The left-hand side of an assignment must be a variable, property or indexer ReadOnly
        }

        public static void Main()
        {
            Program objp = new ReadOnly_in_CSharp.Program();
            objp.ChangeValue();


            Console.WriteLine(_readonly);
            Console.WriteLine(_const);
            Console.Read();
        }
    }
}