Jakob Busk Sørensen
Jakob Busk Sørensen

Reputation: 6081

The given expression is never of the provided type

I have an abstract class, let's call it Base. I then have a number of classes inheriting from Base, like this example:

public class Actual : Base
{
    ...
}

I want to determine if the actual type (not the abstract base) at runtime is a specific type (using the is keyword). It is done in a method which accepts any class, which inherits from Base:

public void Method(Base input)
{
    if (input.GetType() is Actual)
    {
        // do something
    }
}

This gives me a warning in Visual Studio (2019) stating that:

CS0184: The given expession is never of the provided ('Actual') type

Why is this? The Actual class is only one of many, which inherits from Base. So it is in no way given, that it will be of that type at runtime...

Note:

I have tried to follow Actual by using Ctrl + Click and I have done the same for Base. In both cases I end up at the expected classes. Also, there are no duplicate class names in any of the assemblies which is involved in the solution.

Upvotes: 0

Views: 1787

Answers (1)

Jack J Jun- MSFT
Jack J Jun- MSFT

Reputation: 5986

Based on the advice from CodeCaster, we should use input is Actual instead of input.GetType() is Actual.

Like the following code:

public void Method(Base input)
        {
            if (input is Actual)
            {
                Console.WriteLine("yes");
            }
        }

Also, you can use it like:

        Program p = new Program();
        Actual act = new Actual();
        p.Method(act);

Finally, you will get output "yes".

Upvotes: 1

Related Questions