Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

c# - "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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...