Static const.

  • Thread starter Thread starter Vladimir Bezugliy
  • Start date Start date
V

Vladimir Bezugliy

Why I can't declare a member of class as "static const".
As far as I see I should declare as "static readonly".

class StateObject
{
public static const int BufferSize = 1024;
}


F:\.NET\ChatterBox\MessageListener.cs(15): The constant
'ChatterBox.StateObject.BufferSize' cannot be marked static

Vladimir Bezugliy.
 
Vladimir Bezugliy said:
Why I can't declare a member of class as "static const".
As far as I see I should declare as "static readonly".

class StateObject
{
public static const int BufferSize = 1024;
}


F:\.NET\ChatterBox\MessageListener.cs(15): The constant
'ChatterBox.StateObject.BufferSize' cannot be marked static

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

The following will accomplish what you're trying:
public const int BufferSize = 1024; // const and static
 
Vladimir Bezugliy said:
Why I can't declare a member of class as "static const".
As far as I see I should declare as "static readonly".

From the C# language specification:

<quote>
Even though constants are considered static members, a constant-
declaration neither requires nor allows a static modifier.
</quote>
 
fbhcah,
No!

Const are evaluated at compile time.

Static readonly are evaluated at runtime.

In other words if you change the value of a public Const in a class library,
you will need to recompile all assemblies that reference that class library.

However if you change the value of a static readonly field, you will only
need to recompile the class library.

Also because static readonly are evaluated at runtime, you can also
calculate their value at runtime using a static constructor or initializer
syntax.

Hope this helps
Jay
 
Back
Top