Hi friends, In this tutorial, I am going to explain the difference between Constant and Readonly in C#. Constant and Readonly both are used to make field constant and their value cannot be modified. Here we will discuss the difference between these keywords.

Difference between Constant and Readonly in C#:

Constant:

Constants in C# are declared using the const keyword and must assign a value at the time of declaration. This value of const field can’t be changed throughout the program (means we cannot reassign a value in const field). The syntax for declaring a Constant in C# is:

Syntax:

access-modifier const data-type variable-name=value

Example:

class ConstantDemo
{
public const int iConstValue=3;
}

class Program
{
static void Main(string[] args)
{
Console.WriteLine(ConstantDemo.iConstValue);
Console.ReadLine();
}
}

We can not declare a constant variable as static. It is static implicitly. This means that we can a constant variable by using the class name.

The value in a const variable is what’s called a “compile-time” value, and is immutable (which means it does not change over the life of the program).

A Constant variable is declared only with the primitive data type like int, string, double, float etc. If we want to declare const for someclass (non-primitive types) we should assign it to null which as of no use.. Also, a constant variable is declared public, private, protected, internal, or protected internal access modifiers. Const field cannot be passed as ref or out parameter.

Key Point about Constant:

  • Constants are declared using const keyword in C#.
  • Constants must assign a value at the time of declaration.
  • The value of const field cannot be changed throughout the program.
  • We can not declare a const field as static. They are static implicitly.
  • the const field cannot be passed as refs or out parameter.

Readonly:

A readonly field can be declared using the readonly keyword. The readonly field can be initialized either at compile (at the time of declaration)or at the instance initialization (in the constructor only non-static). A readonly field can have different value depending upon the number of constructors used. So it may have different values depending upon the instance used. A readonly field can be used as runtime constant. Readonly is not static by default however we can declare a readonly field as static.

Example 1:

Initialize the readonly field at the time of declaration.

class ReadOnlyDemo
{
public readonly int iReadOnlyValue= 10;
}

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

Example 2:

Initialize the readonly field in constructor.

class ReadOnlyDemo
{
public readonly int iReadOnlyValue;

public ReadOnlyDemo()

{

iReadOnlyValue=1;

}
}

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

Key Point about readonly field:

  • Readonly fields are declare using readonly keyword.
  • Readonly fields are initialized at the time of declaration or in the constructor.
  • A readonly field can have different value depending on the constructor used.
  • A readonly field is not static in nature by default. Then can be declared as static expliciely.
  • A readonly field can be passed as ref or out parameter in constructor context.

 

 

59 Comments

  • Unquestionably believe that which you said. Your favorite reason seemed to be on the web the easiest thing to be aware of. I say to you, I certainly get annoyed while people think about worries that they just do not know about. You managed to hit the nail upon the top and also defined out the whole thing without having side-effects , people could take a signal. Will likely be back to get more. Thanks|

  • Definitely believe that which you stated. Your favorite justification seemed to be on the net the easiest thing to be aware of. I say to you, I certainly get annoyed while people consider worries that they just don’t know about. You managed to hit the nail upon the top and also defined out the whole thing without having side-effects , people can take a signal. Will probably be back to get more. Thanks|

  • I think other web-site proprietors should take this web site as an model, very clean and magnificent user genial style and design, let alone the content. You are an expert in this topic!

  • Terrific work! This is the type of info that should be shared around the web. Shame on Google for not positioning this post higher! Come on over and visit my website . Thanks =)

  • F*ckin’ awesome things here. I’m very happy to peer your article. Thank you so much and i am looking ahead to touch you. Will you kindly drop me a mail?

  • Today, I went to the beachfront with my children. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is completely off topic but I had to tell someone!

  • Excellent post. I was checking continuously this blog and I’m impressed! Extremely helpful information specially the last part 🙂 I care for such info a lot. I was looking for this particular info for a long time. Thank you and best of luck.

  • You can definitely see your expertise within the work you write. The sector hopes for even more passionate writers like you who aren’t afraid to say how they believe. All the time go after your heart.

  • I appreciate, cause I found exactly what I was looking for. You’ve ended my 4 day long hunt! God Bless you man. Have a great day. Bye

  • Hello I am so delighted I found your web site, I really found you by accident, while I was looking on Aol for something else, Anyhow I am here now and would just like to say cheers for a fantastic post and a all round entertaining blog (I also love the theme/design), I don’t have time to read it all at the minute but I have saved it and also added your RSS feeds, so when I have time I will be back to read much more, Please do keep up the fantastic job.

  • I just wanted to type a quick note so as to say thanks to you for these stunning strategies you are posting on this website. My prolonged internet lookup has now been rewarded with excellent concept to exchange with my co-workers. I ‘d assert that many of us website visitors are unequivocally fortunate to be in a wonderful community with very many wonderful people with valuable ideas. I feel really privileged to have discovered your web site and look forward to some more cool moments reading here. Thank you again for all the details.

  • This design is wicked! You most certainly know how to keep a reader amused. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Great job. I really loved what you had to say, and more than that, how you presented it. Too cool!

  • Most of whatever you point out is supprisingly legitimate and it makes me wonder why I hadn’t looked at this in this light previously. This piece truly did turn the light on for me personally as far as this particular issue goes. Nevertheless at this time there is one particular position I am not necessarily too cozy with and while I attempt to reconcile that with the actual main theme of the issue, let me observe what the rest of your readers have to point out.Well done.

  • I like reading an article that can make men and women think. Also, thanks for allowing me to comment!|

  • Great post. I was checking continuously this blog and I am impressed! Very useful info specifically the last part 🙂 I care for such info much. I was seeking this certain information for a long time. Thank you and best of luck.

  • Woah! I’m really enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between user friendliness and visual appeal. I must say that you’ve done a superb job with this. Also, the blog loads super quick for me on Internet explorer. Exceptional Blog!|

  • Greetings! Very helpful advice in this particular post! It is the little changes which will make the greatest changes. Thanks a lot for sharing!|

  • I truly wanted to construct a simple note to be able to appreciate you for all the superb ideas you are sharing on this website. My time consuming internet research has now been compensated with high-quality insight to write about with my neighbours. I ‘d assume that many of us site visitors actually are extremely endowed to live in a decent community with very many perfect people with valuable methods. I feel really happy to have encountered your webpage and look forward to so many more cool moments reading here. Thanks a lot once again for everything.

  • It’s a shame you don’t have a donate button! I’d definitely donate to this superb blog! I suppose for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to new updates and will share this blog with my Facebook group. Chat soon!

  • Hey very nice web site!! Guy .. Beautiful .. Amazing .. I will bookmark your website and take the feeds additionally? I’m glad to find numerous helpful information here within the post, we’d like develop extra techniques in this regard, thank you for sharing. . . . . .|

  • A fascinating discussion is worth comment. I think that you need to publish more on this topic, it may not be a taboo matter but typically people do not discuss these subjects. To the next! All the best!!|

  • 986508 606522I truly enjoyed reading this internet site, this is fantastic blog. 198870

  • Have you ever thought about including a little bit more than just your articles? I mean, what you say is fundamental and everything. Nevertheless think of if you added some great images or videos to give your posts more, “pop”! Your content is excellent but with images and clips, this website could undeniably be one of the best in its niche. Terrific blog!

  • I simply needed to say thanks again. I’m not certain what I would’ve sorted out in the absence of the type of opinions discussed by you relating to such a field. It actually was the troublesome concern for me personally, but being able to see your skilled tactic you solved it took me to weep for fulfillment. Extremely happy for your information and in addition sincerely hope you recognize what a great job you are carrying out educating others thru your web site. Most probably you haven’t encountered all of us.

  • Whats up very nice website!! Man .. Excellent .. Wonderful .. I’ll bookmark your web site and take the feeds additionally…I’m happy to find so many useful information right here within the post, we need work out more techniques on this regard, thanks for sharing. . . . . .

  • Hey very cool web site!! Man .. Excellent .. Amazing .. I will bookmark your site and take the feeds also…I am happy to find numerous useful information here in the post, we need develop more techniques in this regard, thanks for sharing. . . . . .

  • Pretty section of content. I simply stumbled upon your weblog and in accession capital to assert that I get actually enjoyed account your blog posts. Anyway I’ll be subscribing to your feeds or even I fulfillment you access persistently fast.

  • I’d like to thank you for the efforts you have put in penning this site. I really hope to see the same high-grade content from you later on as well. In fact, your creative writing abilities has inspired me to get my very own blog now ;)|