How can I cast an Interface as its type in c#?
.net, c#, casting, interface, polymorphism
Solution
When you hit a situation where you need to do this, it means you're doing something wrong. You need to back up and figure out why your design demands that you do this. If you find yourself stuck there, I strongly recommend you post a new question to get help with the design - there are a lot of smart people here who can help.
To answer your question directly, no - you cannot do this without some kind of if/else or conditional, because you have to be explicit with static types. You could use reflection to call the method, but since you seem to need to call something the interface does not support - but some objects do - you would need to code a per-static-type condition anyway to call that method. Just code the types directly.
Edit: per the discussion in the comments, the best solution to this is to add a second interface to the classes which have this other property or method. Then you can do a simple check:
IPreDisplay display = cb.PreDisplay;
IOtherInterface displayAsOther = display as IOtherInterface;
if(displayAsOther != null)
{
displayAsOther.OtherMethod();
}
Problem
I have a property that returns an interface. During debugging I can break on what was returned and while it is the interface, Visual Studio is smart enough to know the derived type that it actually is. I assume it's using reflection or something. I'm not sure. My question is, can I have that same info available to me at runtime so I can create a variable of the appropriate type and cast the interface as that? Here is what I am saying: ``` IPreDisplay preDisplay = cb.PreDisplay; ``` If preDisplay is a RedPreDisplay I would like to be able to code ``` RedPreDisplay tmp = preDisplay as RedPreDisplay; ``` Or if preDisplay were a GreenPreDisplay... ``` GreenPreDisplay tmp = preDisplay as GreenPreDisplay; ``` etc... I would like to avoid a messy switch statement if possible, and If I could use generics that would be great. If you have any advice or examples of how I can do this, please share.