What's the use of value types in .Net?

The official guidelines suggest that there can be very few practical uses for these. Does anyone have examples of where they've put them to good use?


Au Contrare... you'll find C/C++ people flocking to structs aka value types.
An example would be data packets. If you have a large number of data packets to transfer/transmit, you'd use value structs to model your data packets.
reason: Turning something into a class adds an overhead of (approx 8-16 Bytes I forget) of overhead in the object header in addition to the instance data. In scenarios where this is unacceptable, value types are your safest bet
Another use would be situations where you need value type semantics - once you create-initialize a object, it is readonly/immutable and can be passed around to n clients.


For the most part, it's good to emulate the behaviour of the framework. Many elementary data types such as int s are value types. If you have types that have similar properties, use value types. For example, when writing a Complex data type or a BigInteger , value types are the logical solution. The same goes for the other cases where the framework used value types: DateTime , Point , etc.

When in doubt, use a reference type instead.


Enums are first class citizens of .NET world. As for structures I found that in most cases classes can be used, however for memory-intense scenarios consider using structures. As a practical example I used structures as data structures for OSCAR (ICQ) protocols primitives.

链接地址: http://www.djcxy.com/p/82804.html

上一篇: 结构总是堆栈分配还是有时堆分配?

下一篇: .Net中值类型的用法是什么?