简体   繁体   中英

“Primitive types” versus “built-in value types”

I recently caught an exception in C# while using the Array.SetValue(Int32) method. The exception was:

Cannot widen from source type to target type either because the source type is a not a primitive type or the conversion cannot be accomplished.

The reference to the word "primitive" surprised me a bit because I thought the tendency was to refer to these types as built-in types, also that the term "primitive type" was an informal term. What is the difference between "primitive" types and "built-in value types"? I don't find a definition of primitive types in the C# language specification.

Primitive Types are not defined in the C# Language Specification. They are instead defined in .NET itself, and the best reference for primitive types is to look straight at Type.IsPrimitive on MSDN. Specifically, the Remarks section lists the primitive types that are available.

So that we've got a complete reference here, these are the primitive types defined in the CLI Spec (Section I.8.2.2):

Contrary to popular belief, just because a type has a corresponding keyword does not make it a primitive type, the best example is probably string .

Value types, on the other hand, may or may not be primitives also. There are lots of value types "built-in" to the .NET Framework in addition to those defined in the CLI Spec, but they are not classed as primitives. A good example is DateTime , which is a struct provided by the .NET Framework, by that definition it could be considered a "built-in value type". You can read more about value types (which will of course cover the built-in ones also) here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM