Checking an instance on a dynamic type
I have the following:
interface IViewable {}
class Node {}
class DecisionNode : Node, IViewable {}
In one segment of my application, I have the following method to which I am passing an instance of DecisionNode:
void handleNode (Node node)
{
// ...
var viewable = node as IViewable;
// ...
}
The problem is that this doesn't seem to check if the dynamic / runtime type node
is actually a subclass IViewable
. It correctly rules out that this is the case for static type ( node
), but that's not what I want to test. I get the same result if I try to use or use is
.
I was advised to use GetType ().IsAssignableFrom()
to solve this problem, but the platform I am using (Xamarin) does not allow this.
Is there another way to check if the dynamic type of my object can be handled as an instance of a given type?
source to share
as
performs type checking; it just returns null
if validation fails, which you can check with if
:
if(viewable != null) {
...
} else {
...
}
Re:
node
cannot be regarded as an instanceIViewable
It is right; however it viewable
may be; just run the IViewable
linked code with viewable
.
If you want to argue that this transformation should always work; just click:
var viewable = (IViewable)node;
As an example, the following outputs:
DecisionNode: True
Node: False
code:
class Program
{
static void Main()
{
var prog = new Program();
prog.handleNode(new DecisionNode());
prog.handleNode(new Node());
}
void handleNode(Node node)
{
var viewable = node as IViewable;
System.Console.WriteLine("{0}: {1}",
node.GetType().Name,
viewable != null);
}
}
interface IViewable { }
class Node { }
class DecisionNode : Node, IViewable { }
If you can't get it to work, consider:
// play hunt the interface
if(viewable == null) {
foreach(Type iType in node.GetType().GetInterfaces()) {
if(iType.Name == "IViewable") {
Console.WriteLine("{0} vs {1}",
iType.AssemblyQualifiedName,
typeof(IViewable).AssemblyQualifiedName);
}
}
}
source to share
as
performs type checking.
as
the keyword is doing some kind of "soft" casting it tries and if it fails it falls back to null
The as operator as a casting operation. However, if conversion is not possible because it returns null instead of throwing an exception.
So check null
and you will know if there is viewable
null
or is not the requested type:
var viewable = node as IViewable;
if (viewable != null)
{
// go ahead!
}
Or check with is
:
if (node is IViewable)
{
var viewable = (IViewable)node; // this is safe now
// go ahead!
}
source to share