0

How to implement operator is with a type, that I got from reflection (since that type marked as internal)?

My code:

Type someType = someObj.GetType();
Type runtimeType = Assembly.GetAssembly(typeof(string)).GetType("System.RuntimeType");  //Marked as internal

if (someType is runtimeType)    //Not compiling...
{
    //To do something
}

I wrote some hackery code, but may be there is a better solution than that:

private static bool _isThat<T, K>(T obj) { return obj is K; }

private static readonly MethodInfo _isThatMethodInfo = typeof(Program).GetMethod("_isThat", 
    BindingFlags.NonPublic | BindingFlags.Static);

public static bool IsThatType<T>(T obj, Type type)
{
    return type == null || obj == null ? false
        : (bool)_isThatMethodInfo.MakeGenericMethod(typeof(T), type).Invoke(null, new object[] { obj });
}

Unfortunately, method IsSubclassOf returns false if someType == runtimeType.

Magnetron
  • 7,495
  • 1
  • 25
  • 41
Tadeusz
  • 6,453
  • 9
  • 40
  • 58
  • How about `(someType == runtimeType) || (someType.IsSubclassOf(runtimeType))`? – Magnetron Mar 12 '21 at 16:20
  • 2
    Use `runtimeType.IsAssignableFrom(someType)`. Note that these are [conceptually different](https://stackoverflow.com/a/17726539/5394572), but then that's expected because reflection is conceptually different. – madreflection Mar 12 '21 at 16:45
  • 2
    @Magnetron `IsAssignableFrom` probably better, as it takes into account things like covariance – Charlieface Mar 12 '21 at 17:00

0 Answers0