Constants vs Readonly in C#


Constants

A constant is one which has a never changing value. When defining a constant  its  value must be determinable at the compile time. The compiler then saves this information in the metadata of the assembly. Defining a constant causes creation of metadata.You can define the constants for only the CLR primitive types like string,int ,bool,Double etc…

Readonly

The difference between a constant and a readonly field is that the value of the readonly field is determined at the runtime. So the class containing this field can modify it.This field is used if we doesnt know the value at compile time.

A typical example can be let us suppose that we have a string field called “Location” which displays “Country” , “State” or “City” based on the user selection. The value of the string  can only be detemined at the runtime but not at the compile time. In this case the “Location” field can be marked as read only. As readonly is generally used for fields you can use it for any data type. Also read only fields can only be written with in a constructor method.

To summarize, a readonly variable can only be modified during the declaration or in the constructor of
a class or struct. This differs from a const variable, which cannot be modified anywhere in the code.
 

Advertisements
This entry was posted in C#. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s