I’m having a bit of an issue casting my objects in C# to be able to use the additional object methods besides the ones declared in the interface. Below is a simple example of what I am speaking about.
public interface IShape
{
void Print();
}
public class Square : IShape
{
#region IShape Members
public void Print()
{
HttpContext.Current.Response.Write("Square Print Called");
}
#endregion
public void PrintMore()
{
HttpContext.Current.Response.Write("Square Print More Called");
}
}
Why when this code below is called am I not able to access PrintMore()?
IShape s = (Square)shape;
s.PrintMore() // This is not available. only Print() is.
Any help and explanation would be helpful?
Your
svariable is still of typeIShape. Just because you happen to have used a cast when assigning to it doesn’t change the type as far as the compiler’s concerned. You’d need:Of course, this will only work if
shapereally is aSquare(assuming there aren’t custom conversions going on).I would advise you to think carefully before going down this route though. Usually a cast like this indicates that you’re breaking abstraction somewhat – if you only know about
shapeas anIShape, you should (usually) be able to do what you need just with the members ofIShape. If that’s not the case, you can:IShapemore powerful (give it more members)Squareinstead of anIShape