Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to see if an object inherits IDictionary without generic type parameters?

Tags:

c#

I am testing object like this:

if (item is IDictionary<object, object>)

But that doesn't match all of the other combination of types <sting, object>, <int, string> etc...

I just want to know if it has implemented the interface regardless of what generic types it is using.

I found an example that said it was possible doing something like:

dictionary.GetType().GetInterfaces().Any(x => x.GetGenericTypeDefinition == typeof(IDictionary<>));

But I still have to specify the type signature or it is not valid.

Is it possible to make a statement that checks the interface without having to specify the type?

like image 915
Guerrilla Avatar asked May 01 '15 18:05

Guerrilla


People also ask

Is it possible to inherit from a generic type?

An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.

How do you check if an object is a specific type?

To determine whether an object is a specific type, you can use your language's type comparison keyword or construct.

How do you know if a type is generic?

To examine a generic type and its type parametersGet an instance of Type that represents the generic type. In the following code, the type is obtained using the C# typeof operator ( GetType in Visual Basic, typeid in Visual C++). See the Type class topic for other ways to get a Type object.


1 Answers

You are close, you really just need to fix up the syntax:

dictionary.GetType().GetInterfaces().Any(x => x.GetGenericTypeDefinition() == typeof(IDictionary<,>))

Note the () after GetGenericTypeDefinition, and the comma inside of the <>.

like image 66
Steve Czetty Avatar answered Oct 12 '22 23:10

Steve Czetty