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?
--
Regards
Konrad Viltersten
--------------------------------
sleep - a substitute for coffee for the poor
ambition - lack of sense to be lazy
Peter Duniho - 16 Mar 2008 01:07 GMT
> I used the following code.
>
[quoted text clipped - 9 lines]
> 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
Arne Vajhøj - 16 Mar 2008 01:30 GMT
> I used the following code.
>
[quoted text clipped - 9 lines]
> one get
> around it?
No need to - const is implicit static - it is per class
not per instance.
Arne
K Viltersten - 16 Mar 2008 09:22 GMT
>> I used the following code.
>>
[quoted text clipped - 11 lines]
> No need to - const is implicit static - it is
> per class not per instance.
Ah, all right, then. Thanks.
--
Regards
Konrad Viltersten
--------------------------------
sleep - a substitute for coffee for the poor
ambition - lack of sense to be lazy
Ben Voigt [C++ MVP] - 17 Mar 2008 18:59 GMT
>> I used the following code.
>>
[quoted text clipped - 12 lines]
> 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.
> Arne
K Viltersten - 17 Mar 2008 21:27 GMT
>>> I used the following code.
>>>
[quoted text clipped - 16 lines]
> readonly is more or less like C++ const, C#
> const is like C++ static const.
Ah, even more great info. Thanks!
--
Regards
Konrad Viltersten
--------------------------------
sleep - a substitute for coffee for the poor
ambition - lack of sense to be lazy