0

I am getting expectedExceptionType is a 'field' but used like a 'type' error from the if (exception is expectedExceptionType) line. However as you can see it is a Type. What is the problem here?

I am using Visual Studio 2013 with .NET 4.5

public sealed class ExpectedInnerException : ExpectedExceptionBaseAttribute 
{
    private Type expectedExceptionType;
    private string expectedExceptionMessage;

    public ExpectedInnerException(Type expectedExceptionType, string expectedExceptionMessage)
    {
        this.expectedExceptionType = expectedExceptionType;
        this.expectedExceptionMessage = expectedExceptionMessage;
    }

    protected override void Verify(Exception exception)
    {
        if (exception is expectedExceptionType)
        {

        }
        //Some other code
    }
}
Nuri Tasdemir
  • 9,720
  • 3
  • 42
  • 67

3 Answers3

5

expectedExceptionType is an instance of the type Type, not a compile-time-type in itself. Thus write this instead:

protected override void Verify(Exception exception)
{
    if (exception.GetType() == expectedExceptionType)
    {

    }
    //Some other code
}

EDIT: If your type is a subclass from that one reflected by expectedExceptionType you can check for IsAssignableFrom:

if (exception.GetType().IsAssignableFrom(expectedExceptionType.GetType()))
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
2

HimBromBeere told you the reason, but not the best way to solve this, since checking on the type directly won't work with interfaces and derived instances.

This code does:

protected override void Verify(Exception exception)
{
    if (exception.GetType().IsAssignableFrom(expectedExceptionType))
    {

    }
    //Some other code
}
Community
  • 1
  • 1
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
0

The is operator expects a type expression, not a variable/field with System.Type type.

The compatible solution:

protected override void Verify(Exception exception)
{
    if (expectedExceptionType.IsAssignableFrom(exception.GetType()))
    {

    }
    //Some other code
}
György Kőszeg
  • 17,093
  • 6
  • 37
  • 65