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.
A value type is usually whatever type reside on the Stack . A primitive type is a type defined at the programming language level, often it is even a value type, directly supported by the compiler of the language.
Primitive values can be stored in variables directly. Objects, on the other hand, are stored as references. A variable that has been assigned an object does not store that object directly, it stores the memory address of the location that the object exists at.
In computer science, primitive data types are a set of basic data types from which all other data types are constructed. Specifically it often refers to the limited set of data representations in use by a particular processor, which all compiled programs must use.
The java. lang. Class. isPrimitive() method can determine if the specified object represents a primitive type.
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):
Boolean
Byte
SByte
Int16
UInt16
Int32
UInt32
Int64
UInt64
IntPtr
UIntPtr
Char
Double
Single
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With