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

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Buy Books Online at Best Prices

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.