Use of IsAssignableFrom and "is" keyword in C#

C#asp.net MvcCastingUnity ContainerReflection

C# Problem Overview


While trying to learn Unity, I keep seeing the following code for overriding GetControllerInstance in MVC:

if(!typeof(IController).IsAssignableFrom(controllerType)) { ... }

this seems to me a pretty convoluted way of basically writing

if(controllerType is IController) { ... }

I appreciate there are subtle differences between is and IsAssignableFrom, ie IsAssignableFrom doesn't include cast conversions, but I'm struggling to understand the implication of this difference in practical scenarios.

When is it imporantant to choose IsAssignableFrom over is? What difference would it make in the GetControllerExample?

if (!typeof(IController).IsAssignableFrom(controllerType))
      throw new ArgumentException(...);
return _container.Resolve(controllerType) as IController;
            

C# Solutions


Solution 1 - C#

It's not the same.

if(controllerType is IController)

would always evaluate to false since controllerType is always a Type, and a Type is never an IController.

The is operator is used to check whether an instance is compatible to a given type.

The IsAssignableFrom method is used to check whether a Type is compatible with a given type.

Solution 2 - C#

typeof(IController).IsAssignableFrom(controllerType) tests a Type against the interface. The is operator tests an instance against the interface.

Solution 3 - C#

is keyword is only applicable for instances while Type.IsAssignableFrom() is only applicable for types.

example of is

string str = "hello world";
if(str is String)
{
    //str instance is of type String
}

Note that str is an instance and not the type.

example of IsAssignableFrom()

string str = "hello world";
if(typeof(Object).IsAssignableFrom(str.GetType()))
{
    //instances of type String can be assigned to instances of type Object.
}

if(typeof(Object).IsAssignableFrom(typeof(string)))
{
    //instances of type String can be assigned to instances of type Object.
}

Note that, argument to IsAssignableFrom() is not the instance of String, it's the Type object representing String type.

Solution 4 - C#

A notable difference is also that 'is' makes intuitive sense for testing inheritance or interface implementation, whereas IsAssignableFrom makes anything but sense on the face of it. The name of the Type.IsAssignableFrom method is vague and confusing when applied to testing inheritance or detecting interface implementations. The following wrapper for these purposes would make for much more intuitive, readable application code:

    public static bool CanBeTreatedAsType(this Type CurrentType, Type TypeToCompareWith)
    {
        // Always return false if either Type is null
        if (CurrentType == null || TypeToCompareWith == null)
            return false;

        // Return the result of the assignability test
        return TypeToCompareWith.IsAssignableFrom(CurrentType);
    }

Then, one can have more understandable client syntax like:

    bool CanBeTreatedAs = typeof(SimpleChildClass).CanBeTreatedAsType(typeof(SimpleClass));
    CanBeTreatedAs = typeof(SimpleClass).CanBeTreatedAsType(typeof(IDisposable));

The advantage of this method instead of the 'is' keyword is that it can be used at run-time to test unknown, arbitrary Types, whereas the 'is' keyword (and a generic Type parameter) requires compile-time knowledge of specific Types.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfearofawhackplanetView Question on Stackoverflow
Solution 1 - C#Mark SeemannView Answer on Stackoverflow
Solution 2 - C#FemarefView Answer on Stackoverflow
Solution 3 - C#this. __curious_geekView Answer on Stackoverflow
Solution 4 - C#Mark JonesView Answer on Stackoverflow