Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic dictionary with value type keys and reference type values

What code do you write to constrain a generic dictionary named MyDictionary to have value-type keys with reference type values?

I think this was my answer:

public class MyDictionary<Tkey,TValue>:Dictionary<Tkey,TValue>
where Tkey:struct
where TValue:class
{

}

But I'm not sure if this is the right answer..

like image 567
Nick Avatar asked Aug 16 '26 04:08

Nick


1 Answers

Looks fine to me. One small caveat, you won't be able to use Nullable types (e.g. int?) as either keys or values in such a dictionary.

From Constraints on Type Parameters:

where T: struct The type argument must be a value type. Any value type except Nullable can be specified.

where T: class The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.

like image 142
verdesmarald Avatar answered Aug 18 '26 19:08

verdesmarald



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!