Pages

Wednesday, February 22, 2012

Difference between const and readonly in c#

Difference between const and readonly in c#
Following are the difference between const and readonly .
Const: 
1.const can only be initialized at the declaration of the field.
2.const is static by default.
3.Value is evaluated at compile time.
Readonly :
1.Readonly can be initialized either at the declaration or in a constructor.
2.Value is evaluated at run time.
3.Readonly fields can have different values depending on the constructor used.
Example of const and readonly keywords in c# :
class MyClass 
{
     public readonly int y = 20; // Initialize a readonly field
     public readonly int z;

     public const int c1 = 5; // Initialize a const

     public MyClass() 
     {
        z = 24;   // Initialize a readonly instance field in constructor.
     }
}

Related Other posts

11 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. From your discussion I have understood that which will be better for me and which is easy to use. Really, I have liked your brilliant discussion. I will comThis is great helping material for every one visitor. You have done a great responsible person. i want to say thanks owner of this blog.
    Authorized iphone service center in Chennai | iphone service center in chennai | Mobile service center in chennai | Authorized iphone service center in Chennai | iphone service center in chennai

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Thank You ! The Difference between const and readonly are properly explained.

    ReplyDelete
  5. I think you did an awesome job explaining it. Sure beats having to research it on my own. Thanks
    University Of Kota BCOM 1st, 2nd & Final Year Time Table 2020

    ReplyDelete
  6. Hi, I do think this is a great website. I stumbledupon it ?? I am going to return once again since i have book-marked it. Money and freedom is the greatest way to change, may you be rich and continue to help other people.

    CCSU BA 3rd Year Result

    ReplyDelete
  7. Coolearth is one of the leading Healthcare Solution Providers in India. For more information visit Coolearth and get complete information in details.
    Healthcare Solution Providers in India

    ReplyDelete
  8. Nice blog, thank you so much for sharing this valuable information. Visit RP Paper Impex for Printing Paper Manufacturer and Cupstock Paper Cup Manufacturing Paper Manufacturer.
    Printing Paper Manufacturer

    ReplyDelete
  9. Nice Blog! Get leading Fleet Body Branding in India, Food Truck Branding Services, and Industrial Painting Services at Kalakutir. Visit our website for more information in details.
    Fleet Body Branding in India

    ReplyDelete