Gerard Sexton
Gerard Sexton

Reputation: 3210

How to cast a generic type when parameters differ but are convertable?

I have a method parameter that takes IDictionary<string,string> but I would like to pass it an IDictionary<string,JToken> (Newtonsoft.Json).

The cast fails at runtime but since JToken provides both implicit and explicit conversion methods, I thought there might be a way to cast.

How can this cast be achieved?

class MyClass
{
    void Method(IDictionary<string,string> data) {}
}

...
IDictionary<string,JToken> record = ...;
MyClass cls = new MyClass();
cls.Method((IDictionary<string,string>)record);
...

Upvotes: 1

Views: 54

Answers (1)

Jamiec
Jamiec

Reputation: 136134

You cant Cast from one to the other, pretty much the only way is to create a new Dictionary:

IDictionary<string,JToken> record = ...;
MyClass cls = new MyClass();
cls.Method(record.ToDictionary(k => k.Key,v => (string)v.Value));

Upvotes: 5

Related Questions