Nick
Nick

Reputation: 636

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..

Upvotes: 3

Views: 6296

Answers (2)

Arun Kumar
Arun Kumar

Reputation: 1

No Problem. if will perfectly fine.

var c = new Dictionary<MyStruct?, MyClass>();
MyStruct? key = new MyStruct(){ X =5};
var value = new MyClass();
c.Add(key, value);
Console.WriteLine(c[key].Prop);

Upvotes: 0

verdesmarald
verdesmarald

Reputation: 11866

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.

Upvotes: 4

Related Questions