Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of IsAssignableFrom and "is" keyword in C#

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;
like image 476
fearofawhackplanet Avatar asked Jun 10 '10 10:06

fearofawhackplanet


3 Answers

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.

like image 148
Mark Seemann Avatar answered Sep 23 '22 06:09

Mark Seemann


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

like image 41
Femaref Avatar answered Sep 23 '22 06:09

Femaref


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.

like image 40
this. __curious_geek Avatar answered Sep 22 '22 06:09

this. __curious_geek