Nathan Taylor
Nathan Taylor

Reputation: 24606

Comparing generic interface types

I need to detect whether an object of type IDictionary<string, string> is an IDictionary<,> and I'm having trouble coming up with the proper comparison logic.

I have tried the following:

typeof(IDictionary<string, string>)
       .GetInterface(typeof(IDictionary<,>).Name);

and

typeof(IDictionary<string, string>)
       .GetGenericTypeDefinition()
       .GetInterface(typeof(IDictionary<,>).Name);

Calling typeof(Dictionary<string,string>).GetInterface(comparisonType.Name) returns the expected non-null result, but if I compare on the IDictionary<string,string> type, GetInterface() returns null. Likewise, comparing on the GenericTypeDefinition also returns null.

Upvotes: 1

Views: 1328

Answers (2)

Carlo Kok
Carlo Kok

Reputation: 1188

static void Main(string[] args)
    {
        var x = typeof(IDictionary<string, string>);
        var y = typeof(IDictionary<,>);

        Console.WriteLine(x.GetGenericTypeDefinition() == y);
    }

returns true

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

typeof(IDictionary<string, string>).GetGenericTypeDefinition() == typeof(IDictionary<,>)

Upvotes: 9

Related Questions