开发者

constant field member in c#

hi all i am confused const long size =((long)int.Maxvalue+1)/4 how i interprate it... and what will happen when we define static const long开发者_如何学编程 size =((long)int.Maxvalue+1)/4... what is readonly member....


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;
}

can't declare a member of class as "static const".

  • Because member variables declared as "const" are already "static".

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

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;

  public MyClass()
  {
    PI = 3.14159;
  }
}


You can't define static const, since a const is always static. The compiler will generate an error in this situation ('The constant 'XYZ' cannot be marked static').

readonly members can be initialized only once, i.e. either in a constructor, or at the declaration of the field.

The difference between readonly and const is, that a readonly member will be evaluated at run-time, whereas a const will be evaluated at compile-time.


Well the statement is declaring a long constant that has approximately one-fourth value of maximum possible value of int (2^31).

const are anyway static and no need to decorate them as such. Read-only field can be static or instance and can be initialized only once (in constructor - you can of course assign it while declaring but that code goes into constructor only). Constant gets embedded into the code while read-only field would get referred in code (this matters if you are library developer). Also constants can be initialized with constant expressions as deemed by complier while read only fields can be initialized with result of some calculation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜