Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strongly-typed boxed values in .NET

Tags:

.net

clr

boxing

To box a value type you cast it to System.Object - that in itself seems "wrong" to me (because casting should either convert the value to another type (so converting an Int32 to Object should be a data-lossy action, as Object has no instance state of its own) or converting an interface pointer to a parent (which does not affect the state of the object being pointed to and is a compile-time concern). When boxing a value-type in the CLR you're copying the value to the heap and losing interface information at the same time, when you only really want to perform the first task (copying the value to the heap, or at least getting a reference to it).

Java solves this problem with the strong types of Integer and Long. Why doesn't .NET have this?

I have my own collection of utility source code that I like to include in other projects, and they include their own implementations of strongly-typed boxed classes (such as BoxedInt32) which override the implicit and explicit conversion operators so they work the same way as casting to Object does, except without having to actually cast to object (thus preserving type data). So I can do this:

private BoxedInt32 _reference;
public Int32 GetValue{ return _reference; }

So why doesn't .NET, after four major releases, still not have strongly-typed boxed types?

like image 878
Dai Avatar asked Dec 04 '25 13:12

Dai


1 Answers

There would be no point. You would never directly use BoxedInt32, since if you knew the type in advance it would only be sensible to use int instead of the box. So the only interesting case is: when we don't know the type in advance, i.e. when dealing with object. Well, value-type boxing already handles that perfectly, reporting the type as Int32.

The reason the specific boxed versions exist in Java is, in part, because Java generics work very differently via type erasure; however .NET has true generics including for value-types, so this is unnecessary.

You could make your own box:

public class Box<T> where T : struct {
    private readonly T value:
    public Box(T value) { this.value = value; }
    public T Value { get { return value; } }
}

(perhaps adding more features such as conversions / equality): but - again: no point whatsoever. Regular inbuilt boxing already handles this much better.

like image 142
Marc Gravell Avatar answered Dec 06 '25 03:12

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!