0

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?

Jim Fell
  • 13,750
  • 36
  • 127
  • 202
  • I think what you want is this: https://learn.microsoft.com/en-us/dotnet/csharp/pattern-matching#the-is-type-pattern-expression – Rhaokiel Jun 12 '19 at 16:02
  • 5
    It's probably a `RuntimeType`. See [What's the difference between System.Type and System.RuntimeType in C#?](https://stackoverflow.com/q/5737840/1715579) Also, you might want use `typeof(Type).IsAssignableFrom(args[0].GetType())` instead. – p.s.w.g Jun 12 '19 at 16:03
  • "Type" is a type itself, so maybe you rather mean `Debug.Assert(args[0].GetType().Equals(typeof(MyType)));`, where `MyType`is your specific type. Note that your line of code also returns false, if the type of `args[0]` is a class derived from `MyType`. – Heinz Kessler Jun 12 '19 at 16:34
  • 3
    Adding to @p.s.w.g's comment, `args[0] is Type` will return true if `args[0]` is assignable to Type instead of checking if it is exact. – Rhaokiel Jun 12 '19 at 16:49
  • @Rhaokiel Awesome! Post that as an answer, and I'll accept it. – Jim Fell Jun 12 '19 at 21:18

1 Answers1

1

@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

Rhaokiel
  • 813
  • 6
  • 17