Difference between const and readonly in c#.


Hi

Const and readonly perform a similar function on data members, but they have a few important differences.

Const

A constant member is defined at compile time and cannot be changed at runtime. Constants are declared as a field, using the const keyword and must be initialized as they are declared. For example;

public class MyClass
{
public const double PI = 3.14159;
}

PI cannot be changed in the application anywhere else in the code as this will cause a compiler error.

Constants can be marked as public, private, protected, internal, or protected internal.

ReadOnly

A read only member is like a constant in that it represents an unchanging value. The difference is that a readonly member can be initialized at runtime, in a constructor as well being able to be initialized as they are declared. For example:

public class MyClass
{
public readonly double PI = 3.14159;
}

or

public class MyClass
{
public readonly double PI;

public MyClass()
{
PI = 3.14159;
}
}

Advertisements

One Response to “Difference between const and readonly in c#.”

  1. automaty samosprzedajace Says:

    Everything is very open with a clear explanation of the issues.
    It was really informative. Your website is extremely helpful.
    Many thanks for sharing!


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

%d bloggers like this: