Use cases for boxing a value type in C#?

后端 未结 9 1129
既然无缘
既然无缘 2021-02-05 23:36

There are cases when an instance of a value type needs to be treated as an instance of a reference type. For situations like this, a value

9条回答
  •  粉色の甜心
    2021-02-05 23:59

    I would recommend you 2 nice articles of Eric Lippert

    http://blogs.msdn.com/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx

    http://blogs.msdn.com/ericlippert/archive/2009/05/04/the-stack-is-an-implementation-detail-part-two.aspx

    Here is the quote that I would 100% agree with

    Using the stack for locals of value type is just an optimization that the CLR performs on your behalf. The relevant feature of value types is that they have the semantics of being copied by value, not that sometimes their deallocation can be optimized by the runtime.

    In 99% applications developers should not care about why Value types are in stack and not in the heap and what performance gain could we have here. Juts have in mind very simple rules:

    1. Avoid boxing/unboxing when not necessary, use generics collections. Most problems occurs not when you define your own types, but when you use existing types inproperly (defined by Microsoft or your collegues)
    2. Make your value types simple. If you need to have a struct with 10-20 fields, I suppose you'ld better create a class. Imagine, all that fields will be copied each time when you occasionally pass it a function by value...
    3. I don't think it is very useful to have value types with reference type fields inside. Like struct with String and object fields.
    4. Define what type you need depending on required functionality, not on where it should be stored. Structs have limited functionality comparing to classes, so if struct cannot provide the required functionality, like default constructor, define class.
    5. If something can perform any actions with the data of other types, it is usually defined as a class. For structs operations with different types should be defined only if you can cast one type to another. Say you can add int to double because you can cast int to double.
    6. If something should be stateless, it is a class.
    7. When you are hesitating, use reference types. :-)

    Any rules allows exclusions in special cases, but do not try to over-optimize.

    p.s. I met some ASP.NET developers with 2-3 years experience who doesn't know the difference between stack and heap. :-( I would not hire such a person if I'm an interviewer, but not because boxing/unboxing could be a bottleneck in any of ASP.NET sites I've ever seen.

提交回复
热议问题