Sunday, August 25, 2013

Difference Between Const, ReadOnly and Static in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StaticReadOnlyConstant
    class Program
        public static string str;                   //Ok
        //public static string str="Static";        //Ok
        static void Main(string[] args)
            str = "Kunal Maurya";

            //Console.WriteLine(ReadOnly.str);    //Ok cant access without object it is instance member
            ReadOnly ro = new ReadOnly();

            Console.WriteLine(Constant.str);    //Ok
            Constant co = new Constant();
            //Console.WriteLine(co.str);          //Not Ok const variables are class members like static, it has one instance only
    public class ReadOnly
        //spublic readonly string str;     //Ok
        public readonly string str="ReadOnly";
        public ReadOnly()
            str = "Kunal Maurya"//Ok readonly can be modified inside the constructor
        public void Modify()
            //str = "Kunal Maurya";  //Ok readonly can not be modified any where except declaration time and inside constructor
    public class Constant
        //public const string str;     //Not Ok must be initialize at declaration time
        public const string str = "ReadOnly"; //Ok
        public Constant()
            //str = "Kunal Maurya";  //Not Ok const can not be modified any where except declaration time

No comments:

Post a Comment