Constructor Questions and Answers

7 Best Differences between constant, readonly and static in C#?

Constant keyword:-

The const keyword is by default static. The value of your const property is set at compile/initialize time and can't change/ modified at run-time i.e.

public class Constants
{
   public const string ICONSTVALUE = "Const";
}


Read-only keyword:-

The read only keyword can be declared as static but not necessary. No need to initialize at the time of declaration. Its value can be changed using constructor i.e.

public class ConstVsReadonly
{
    public readonly string IREADONLVALUE;
    public ConstVsReadonly()
    {
        IREADONLVALUE = "Readonly";
    }
}

For example for both const and read only keyword:-
public class ConstVsReadonly
{
   public const string ICONSTVALUE = "Const";
   public readonly string IREADONLVALUE;
   public ConstVsReadonly()
   {
      IREADONLVALUE = "Readonly";
   }
}

Static keyword:-

The static keyword is used to declare a static member. If you are declaring a class as a static then in this class all members must be static.

The static keyword can be used with classes, fields, operators, events, methods and It cannot be used with indexers, destructors etc.


For example as,

class A
{
        static int a = 10;
        int b = 20;
        public static void Print()
        {
            Console.WriteLine(a);
            Console.WriteLine(b); //error, shere access only static members.
        }
}

Key point of static keyword as,
















I hope you are enjoying with this post! Please share with you friends. Thank you!!
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

7 Best Differences between constant, readonly and static in C#? 7 Best Differences between constant, readonly and static in C#? Reviewed by Anil Singh on 10:00 AM Rating: (5)
www.code-sample.com/. Powered by Blogger.
^