In C# are the terms “Primitive” and “Literal” interchangeable?

前端 未结 8 737
[愿得一人]
[愿得一人] 2021-02-07 20:43

A discussion earlier today led me to question whether or not my understanding of primtives and literals is correct.


My understanding is that a literal type is spec

8条回答
  •  死守一世寂寞
    2021-02-07 21:37

    I think that your understanding is mostly correct. As winSharp93 said, literals are values which themselves have types, but there's no such thing as a "literal type". That is, while you can have string literals, strings are not a "literal type". As you have guessed, what defines a literal is that the value is directly written down in source code, although your requirement that no type needs to be specified seems overly strict (e.g. F# has array literals, and can infer the type of the array literal [| 1; 2; 3 |], but cannot necessarily infer the type of the empty array literal [| |]).

    Unfortunately, I don't think that there is a well-agreed-upon definition of what makes a primitive. Certainly, as Jon Skeet points out, the CLR has its own definition of primitiveness (Type.IsPrimitive), which rules out strings. However, other reputable sources consider string and even object to be primitive types within C#. I prefer this definition, since there is built-in support in C# for strings, such as the use of the + operator for concatenation and the use of == as value equality rather than reference equality, as well as the fact that the string type can be referred to using the short form string rather than having to use the full name System.String.

提交回复
热议问题