Discussion:
"const" with class types, why does it compile?
(too old to reply)
Stefan Ram
2017-04-02 20:34:09 UTC
Permalink
I am reading the C# Language Specification Version 5.0,
where it is written:

»Through const declarations it is possible to declare
constants of the simple types (§10.4). It is not
possible to have constants of other struct types, but a
similar effect is provided by static readonly fields.«.

But why does the following program compile here?
(String is /not/ a simple type, it's a class, according
to the C# Language Specification Version 5.0.)

Program.cs

public static class Program
{ public static void Main()
{
const string lkw = "Lastkraftwagen";
global::System.Console.WriteLine
( $"Ein {lkw}-Fahrer lebt in seinem Fahrzeug." ); }}

transcript

Ein Lastkraftwagen-Fahrer lebt in seinem Fahrzeug.
Arne Vajhøj
2017-04-02 20:45:13 UTC
Permalink
Post by Stefan Ram
I am reading the C# Language Specification Version 5.0,
»Through const declarations it is possible to declare
constants of the simple types (§10.4). It is not
possible to have constants of other struct types, but a
similar effect is provided by static readonly fields.«.
But why does the following program compile here?
(String is /not/ a simple type, it's a class, according
to the C# Language Specification Version 5.0.)
What you quote says that:
- you can have const of the simple types
- you cannot have const of other struct types

It does not say anything about reference types.

If you go to 10.4 as suggested then you find:

<quote>
The type specified in a constant declaration must be sbyte, byte, short,
ushort, int, uint, long, ulong, char, float, double, decimal, bool,
string, an enum-type, or a reference-type.
</quote>

Arne

Continue reading on narkive:
Loading...