Static constants in a class not allowed

P

Peter Duniho

I used the following code.

class C {private const int NUMBER = 6;}

After a while, i realized that NUMBER will not only be constant but also
equal
for any instance of C. So, i wanted to make it shared for all objects of
type C
but the compiler complained.

Apparently it's not allowed to put such members as static. Why? How can
one get
around it?

You don't need to get around it. "static" only applies to data members.
A "const" member is a compile-time constant and is simply hard-coded into
the code where it's used when the code is compiled.

This is either a good thing or a bad thing, depending on what you want to
do. It means that code that uses your assembly will determine that
constant at the time it's compiled, and so even if the assembly is changed
later, it won't be updated. Some times this is what you want. Some times
it's not. :)

Since your code specified the constant as "private", this should be a moot
point. The only code that will ever see the constant is code that's
compiled where the constant is declared.

Pete
 
K

K Viltersten

I used the following code.

class C {private const int NUMBER = 6;}

After a while, i realized that NUMBER
will not only be constant but also equal
for any instance of C. So, i wanted to
make it shared for all objects of type C
but the compiler complained.

Apparently it's not allowed to put such
members as static. Why? How can one get
around it?
 
A

Arne Vajhøj

K said:
I used the following code.

class C {private const int NUMBER = 6;}

After a while, i realized that NUMBER will not only be constant but also
equal
for any instance of C. So, i wanted to make it shared for all objects of
type C
but the compiler complained.

Apparently it's not allowed to put such members as static. Why? How can
one get
around it?

No need to - const is implicit static - it is per class
not per instance.

Arne
 
B

Ben Voigt [C++ MVP]

Arne said:
No need to - const is implicit static - it is per class
not per instance.

Unlike C++ const which is per instance. C# readonly is more or less like
C++ const, C# const is like C++ static const.
 
K

K Viltersten

I used the following code.
Unlike C++ const which is per instance. C#
readonly is more or less like C++ const, C#
const is like C++ static const.

Ah, even more great info. Thanks!
 

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