Search code examples
c#typesunboxing

Evaluating Boxed Type as Type in C#


My application uses a boxed Type object for which I later need to evaluate that it is of type Type, before unboxing. This is implemented like so...

public void MyFunc(params Object[] args)
{
    Debug.Assert(args[0].GetType().Equals(typeof(Type)));
}

This always evaluates as false, even though I can inspect the argument in the debugger and see that it is correct. Any ideas?


Solution

  • @p.s.w.g pointed out, you are likely trying to compare a RuntimeType to a Type.

    By using pattern matching, you can see if the object in question derives from a type like so:

    args[0] is Type
    

    Microsoft Doc on Pattern Matching