5

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....

Nishant Kumar
  • 5,629
  • 17
  • 63
  • 94

4 Answers4

17

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;
  }
}
Pranay Rana
  • 164,177
  • 33
  • 228
  • 256
0

See here and here. It's a duplicated question. But I don't know how to add hyper links in comments. Anyone tell me?

Community
  • 1
  • 1
Cheng Chen
  • 39,413
  • 15
  • 105
  • 159
  • 1
    something like [ title ] ( url )... from [here](http://meta.stackexchange.com/questions/2115/text-formatting-now-allowed-in-comments-list-of-proven-and-disproven-abilities) – pascal Aug 27 '10 at 05:53
0

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.

Giuseppe Accaputo
  • 2,612
  • 16
  • 22
0

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.

VinayC
  • 42,184
  • 5
  • 54
  • 66