In C# are the terms "Primitive" and "Literal" interchangeable?
I just wanted to inject a quick note here.
The C# language specification clearly defines "literal" -- a literal is a source code representation of a value. Literals are things like true
, 10
, 5.7
, 'c'
, "hello"
and null -- they are text that represents a specific value.
The C# language specification uses the word "primitive" twice; it is never defined and completely vague as to what it could possibly mean.
The C# language spec has no need to use or define the word "primitive" and therefore should not make use of this vague term. I've had a talk with Mads and we've agreed that future editions of the spec will be reworded to eliminate this usage completely.
How other type systems specifications -- the reflection library, the CLI, the VES, and so on -- define the word "primitive" is of course up to them.
Thanks for bringing up the question.
Is my understanding (if not my explanation) correct for the most part?
I do not agree in one point:
A literal is some kind of compile time constant (as "Hello World"
, 5
or 'A'
). However, there are no "Literal-Types"; the literal always is the actual value.
Primitive types are IMO "basic" types like string, int, double, float, short, ...
So primitive have their types of literals connected with them.
Yes, a literal is a value expressed in source code - so while VB supports date/time and XML literals, C# doesn't.
From the C# spec, section 2.4.4:
A literal is a source code representation of a value.
As you say, this is unrelated to value type vs reference type - string is indeed a reference type.
One literal which no-one has mentioned yet it null
by the way...
It's also unrelated to primitive types - from Type.IsPrimitive
:
The primitive types are Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, and Single.
... the C# specification doesn't actually define the idea of a "primitive" type, but note that String
isn't in the list above.
In terms of literals being compile-time constants... in C# every literal has a representation which can be baked directly into the assembly; the extra literals in VB mean they're not constants as the CLR would understand them - you can't have a const DateTime
for example - but they're still literals.