Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's not a stupid question, it's a good one. :)</p> <p>What you're asking for on the interface is commonly referred to as "<a href="http://en.wikipedia.org/wiki/Duck_typing" rel="nofollow noreferrer">duck-typing</a>." It isn't supported right now, but C#4.0 will support it via the new "<a href="https://stackoverflow.com/questions/301479/show-me-the-way-to-use-new-dynamic-keyword-in-c-4-0"><code>dynamic</code></a>" keyword.</p> <p>You've really got three choices that I'm aware of at this point:</p> <ol> <li><p>You can go up the tree until you find the common ancestor (probably <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.component.aspx" rel="nofollow noreferrer"><code>Component</code></a>) and then downcast to your supported types. If the downcast fails, you throw or handle appropriately. </p> <p><strong>Pro:</strong> Minimal code duplication.</p> <p><strong>Con:</strong> You're trading away compile-time type safety for runtime type safety. You have to add error checking/handling for invalid casts.</p> <p><strong>Code:</strong></p> <pre><code>public void UseThumbnail(Component c) { PictureBox p = c as PictureBox; if(p != null) // do whatever // so forth } </code></pre></li> <li><p>You can duplicate functionality as appropriate for everything that you need to implement this functionality for. </p> <p><strong>Pro:</strong> Maintain compile time type safety</p> <p><strong>Con:</strong> 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.</p> <p><strong>Code:</strong></p> <pre><code>public void UsePictureBox(PictureBox p) { // Some code X } public void UseOtherControl(OtherControl p) { // Some code X } </code></pre></li> <li><p>You can create your special interface and subclass the classes you want to support to expose that common functionality.</p> <p><strong>Pro:</strong> You get compile time safety and can program against your new interface.</p> <p><strong>Con:</strong> You have to add an empty subclass for everything you're dealing with, and you need to use them.</p> <p><strong>Code:</strong></p> <pre><code>public class ThumbnailPictureBox : PictureBox, IThumbnail { } </code></pre></li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload