Difference Between Const, ReadOnly & Static

17:58

Introduction

In this post I'm going to explain about the Difference between Const, ReadOnly & Static in C#.

Difference

A. Constants
1. Constants can be assigned values only at the time of declaration
2. Constant variables have to be accessed using "Classname.VariableName"
3. Constants are known at compile time
B. Read Only
1. Read only variables can be assigned values either at runtime or at the time of instance initialization via constructor
2. Read only variables have to be accessed using the "InstanceName.VariableName"
3. Read only variables are known at run time.
C. Static
1. If the static keyword is applied to a class, all the members of the class must be static.
2. Static methods can only access static members of same class. Static properties are used to get or set the value of static fields of a class.
3. Static constructor can't be parameterized.
4. Access modifiers can not be applied on Static constructor, it is always a public default constructor which is used to initialize static fields of the class.

Example

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

namespace Const_vs_Readonly
{
    class Program
    {
        static void Main(string[] args)
        {
            // ReadOnly
            ReadOnlyEx readOnlyInstance = new ReadOnlyEx();
            Console.WriteLine(readOnlyInstance.number);

            ReadOnlyEx differentInstance = new ReadOnlyEx(true);
            Console.WriteLine(differentInstance.number);


            //ConstantEx.number = 9;
            // Const
            Console.WriteLine(ConstantEx.number);

            // Readonly Static
            Readonlystatic obj = new Readonlystatic();
            

            Console.ReadLine();
        }
    }

    class ReadOnlyEx
    {
        public readonly int number = 10;
        public ReadOnlyEx()
        {
            number = 20;
        }
        public ReadOnlyEx(bool IsDifferentInstance)
        {
            number = 100;
        }
    }

    class ConstantEx
    {
        public const int number = 3;
    }

    public class Readonlystatic
    {
        readonly static string number2;
        readonly static string number3 = "Surajit";

        static Readonlystatic()
        {
            number2 = number3;
            number3 = "Surajit Ghosh";
            Console.WriteLine("Readonly static " + number2);
        }
    }

    public static class staticEX
    {
        public static int SS = 80;
        public static int A = 90;

        public static void Access()
        {
            int s = A;
        }
    }
}

Conclusion

Guys hope I explain it peoperly.

You Might Also Like

0 comments