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

前端 未结 8 739
[愿得一人]
[愿得一人] 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.

    0 讨论(0)
  • 2021-02-07 21:38

    Just to add that there is another type that blurs the limit: System.Decimal whose values can be expressed as literals in the C# language, but which is not a .Net primitive type.

    IMHO primitive types could be simply defined as types that directly "exists" in every underlying platform/host: if you've already played with assembly language you know that you have bytes, words, double-words... but you have no strings or decimals.

    Indeed .Net decimals are "emulated" by the .Net runtime and are not directly handled by the hardware which only understands IEEE 754 floating point numbers (float and doubles which are then primitive types).

    By extension of the notion of literal values "Literal types" could be considered as any type whose values can be directly expressed in a given language (C#, VB.Net, CIL...). With this definition literal types would be: all the primitive types + strings + decimals.

    0 讨论(0)
提交回复
热议问题