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;
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.
typeof(IController).IsAssignableFrom(controllerType)
tests a Type
against the interface. The is
operator tests an instance against the interface.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With