what is the difference between const and readonly in c#.net ?

This is a mostly asked question in interviews “what is the difference between const and readonly in c#.net ?”. If you are thinking logically both are same , but once you are really going through each one of it you will come to know the difference. So here we can discuss about the differences between const and Readonly.

Const

  • Constants are static by default.
  • They must have a value at compilation-time.
  • Could be declared within functions.
  • Are copied into every assembly that uses them.
  • Can be used in attributes.



ReadOnly

  • Readonly fields can be initialized only while declaration or in the constructor.
  • Once you initialize aReadonly field, you cannot reassign it.
  • You can use static modifier for Readonly fields
  • Readonly modifier can be used with reference types
  • Readonly modifier can be used only for instance or static fields, you cannot use Readonly keyword for variables in the methods.

Leave a Reply

Your email address will not be published. Required fields are marked *