Static const.

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

C# Learner

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
 
J

Jon Skeet [C# MVP]

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

Jay B. Harlow [MVP - Outlook]

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top