constant and readonly in c#?

Possible Duplicate:
What is the difference between const and readonly?

i have doubt in c# what is difference in constant and readonly explain with simple problem or any reference.


A const is initialized at compile time, and cannot be changed.

A readonly is initialized at runtime, but can be done only one time (in the constructor, or inline declaration).


const is a compile-time constant: the value you give is interpolated into your code as it's compiled. This means that you can only have constant values of types that the compiler understands, for example integers and strings. Unlike readonly, you couldn't assign the result of a function to a const field, for example:

class Foo {
  int makeSix() { return 2 * 3; }
  const int const_six = makeSix(); // <--- does not compile: not initialised to a constant
  readonly int readonly_six = makeSix(); // compiles fine
}

A readonly field, on the other hand, is initialised at runtime, and can have any type and value. The readonly tag simply means that the field can never be re-assigned once it's been set.

Beware, though: a readonly collection or object field can still have its contents changed, just not the identity of the collection that's set. This is perfectly valid:

class Foo {
  readonly List<string> canStillAddStrings = new List<string>();

  void AddString(string toAdd) {
    canStillAddStrings.Add(toAdd);
  }
}

but we would not be able to replace the reference in this case:

class Foo {
  readonly List<string> canStillAddStrings = new List<string>();

  void SetStrings(List<string> newList) {
    canStillAddStrings = newList; // <--- does not compile, assignment to readonly field
  }
}

Constants ( const ) must be known at compile time.

readonly fields can be initialized (and only initialized) with a value known at run time.

链接地址: http://www.djcxy.com/p/21216.html

上一篇: ReadOnly和Const之间的区别?

下一篇: 常量和只读在C#中?