The main purpose of "Dot Net Labs" provide the dot net program. You can learn dot net, .Net Core, C#, SQL, Linq step-by-step.

Sunday, 14 May 2023

What is the difference between readonly and const in C#?


In C# readonly and const are used to define constants but both have some differences. It is the most asked question by the interviewer.


Const

·         Const is used to declare a compile-time constant.

·         Const variable is evaluated at compile-time and cannot be changed at runtime.

·         Const are static by default, so it belongs to the type rather than the instance.

·         Const variables must be initialized with a value at the time of declaration and can only hold simple data types.

 

Example:

using System;

 

namespace SoftwareEngineerDotNet

{

    class MyMainClass

    {

        private const double PI = 3.14;

        static void Main(string[] args)

        {

            const int Age = 20;

            // compile time error.

            // Reassigning a const variable is not allowed

            Age++;

            Console.ReadLine();

        }

    }

}

 

Readonly

·         Readonly keyword is used to declare a runtime constant.

·         Readonly variables can be assigned a value either at the time of declaration or within the constructor of the class.

·         Readonly modifier ensures that the variable's value can only be changed during object initialization or within the constructor. Each instance of the class can have a different value for a readonly field.

 

Example:

using System;

 

namespace SoftwareEngineerDotNet

{

    public class MyClass

    {

        //Some valid scenario to initialize readonly variables

        public readonly int MyReadOnlyField;

        public readonly string MobileNumber = "5487458475";

 

        //readonly fields can be initlized in constructor 

        public MyClass(int value)

        {

            MyReadOnlyField = value;

        }

    }

 

    class MyMainClass

    {

        static void Main(string[] args)

        {

            MyClass myClass = new MyClass(2);

            Console.ReadLine();

        }

    }

}

 

 

0 comments:

Post a Comment

Do not enter spam link

Popular Posts