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?
An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.
To determine whether an object is a specific type, you can use your language's type comparison keyword or construct.
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.
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 <>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With