I’m not really sure how to ask this question. Suppose I have a class that needs to access certain properties of a Control (for example, Visible and Location). Perhaps I want to use the same class to access properties of another item that have the same name, but the class might not derive from Control. So I tried making an interface:
public interface IThumbnail {
bool Visible { get; set; }
int Height { get; set; }
int Width { get; set; }
Image Image { get; set; }
Point Location { get; set; }
event EventHandler Click;
}
Note that, for example, PictureBox happens to implement this interface. However, because the class definition does not say that it implements IThumbnail, I can’t cast PictureBoxes to IThumbnails–I get an InvalidCastException at runtime. But why can’t the CLR ‘figure out’ that PictureBox really does implement IThumbnail (it just doesn’t explicitly say it does).
Also, what should I do to handle this situation? I want a way to access some of the PictureBox’s properties without having my class know it’s modifying a PictureBox.
Thx, Sam
PS- I’m a newbie to interface programming, so I apologize if this is a stupid q.
It’s not a stupid question, it’s a good one. 🙂
What you’re asking for on the interface is commonly referred to as “duck-typing.” It isn’t supported right now, but C#4.0 will support it via the new “
dynamic” keyword.You’ve really got three choices that I’m aware of at this point:
You can go up the tree until you find the common ancestor (probably
Component) and then downcast to your supported types. If the downcast fails, you throw or handle appropriately.Pro: Minimal code duplication.
Con: You’re trading away compile-time type safety for runtime type safety. You have to add error checking/handling for invalid casts.
Code:
You can duplicate functionality as appropriate for everything that you need to implement this functionality for.
Pro: Maintain compile time type safety
Con: You’re duplicating code for different types. This can grow into a significant maintenance burden, especially if you’re handling more than two similar classes.
Code:
You can create your special interface and subclass the classes you want to support to expose that common functionality.
Pro: You get compile time safety and can program against your new interface.
Con: You have to add an empty subclass for everything you’re dealing with, and you need to use them.
Code: