20 December 2010

const vs. readonly


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.
  • Constants must be a value type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, orbool), an enumeration, a string literal, or a reference to null.(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.).
  •  It cant be static.
Example:- 
public class MyClass { public const double PI = 3.14159; }



ReadOnly

  • A read only member is like a constant in that it represents an unchanging value.
  • They are declared as a field, using the readonly keyword and can be initialized at runtime,in a constructor as well being able to be initialized as they are declared
  • They can be declared as static
Example:-

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

No comments:

Post a Comment

Your comments, Feedbacks and Suggestions are very much valuable to me :)

Things are upgraded

My Dear readers, I am really thankful for being supportive all these years. This site was the first blog site I ever created in my life...