Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing base types in reflection

Tags:

c#

reflection

I am calling a method on an assembly using reflection and I need to first compare if one of the parameters for the method has the same base type with the parameter I am passing in for it.

But whenever I call passedInParameter.GetType().BaseType() it returns "

{Name = "MarshalByRefObject" FullName = "System.MarshalByRefObject"}.

Shouldn't it be showing the interface it is implementing?

like image 442
Gho5t Avatar asked Apr 27 '11 12:04

Gho5t


2 Answers

The runtime has helpers for this:

if (typeof(ISomeInterface).IsAssignableFrom(passedInParameter.GetType()))
{
}

Backgrounder:

Interfaces are not basetypes. CLR types cannot have multiple base types.

You should be able to enumerate interfaces implemented by a type, but as you can see from my proposed solution, I don't recommend doing all that

like image 53
sehe Avatar answered Nov 06 '22 02:11

sehe


Interface is not a base class. Class may implement a lot of interfaces If you want to get list of interfaces just use

passedInParameter.GetType().GetInterfaces();

also you can try to use is operator

if(passedInParameter is ISomeInterface)
{
    // do some logic
}

Try to use this code snippet

    ParameterInfo param = paramList[i]; 
    Type type = paramArray[i].GetType();

    bool valid = false;
    if (info.ParameterType.IsInterface)
        valid = type.GetInterfaces().Contains(param.ParameterType);
    else
        valid = type.IsSubclassOf(param.ParameterType);
like image 2
Stecya Avatar answered Nov 06 '22 01:11

Stecya