Is there an equivavlent to C# boxing in D?

H. S. Teoh hsteoh at
Sat Feb 12 00:41:22 UTC 2022

On Sat, Feb 12, 2022 at 12:27:34AM +0000, IGotD- via Digitalmars-d-learn wrote:
> If you want to store a value type on the heap in D you just use "new"
> and a pointer to the type. The same thing in C# would be to wrap the
> value type into an object. However when you do that automatic
> conversion without a cast seems not to be possible (C# also have a
> dynamic type that might solve that but more heavy weight).
> Is there a possibility to wrap a value type in D around the base
> object class that is otherwise used as the class reference type? Would
> this be a way to use D without raw pointers for heap allocated value
> types?

How about this?

final class Boxed(T) {
	T payload;
	alias payload this; // caveat: probably not a good idea in general
	this(T val) { payload = val; }

Boxed!int i = new Boxed!int(123);
int j = i; // hooray, implicit unboxing!
i = 321; // even this works


Computers aren't intelligent; they only think they are.

More information about the Digitalmars-d-learn mailing list