.NET Diary

October 9, 2013

static vs. const vs. readOnly

Filed under: All, ASP.NET, C# — Tags: , , , , , , , — leoullas @ 10:06 pm

static vs. const vs. readOnly static Use of the static modifier to declare a static member, means that the member is no longer tied to a specific object. This means that the member can be accessed without creating an instance of the class. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events.
const • Can’t be static. As it is static by default.
• Value is evaluated at compile time.  So, value can’t be changed at runtime.
• Must be initialized as they are declared.
• Since classes or structures are initialized at run time with the new keyword, and not at compile time, you can’t set a constant to a class or structure.
readonly • Can be either instance-level or static.
• Value is evaluated at run time.  So, value can be changed at runtime.
• Can be initialized in declaration or by code in the constructor.
N.B: readonly exists solely to prevent anyone from, either accidentally or intentionally, changing the value of a variable once it’s set. It is enforced at run-time.
const is similar, but enforced at compile-time. Thus, the value must be set at the time the variable is created.

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: