Note that there are some explanatory texts on larger screens.

plurals
  1. PODefining Generic Objects with class and interface
    text
    copied!<p>I'm having some trouble figuring out how to require a class has extended an interface when working with generic objects. I find this to be difficult to explain, but I want to be able to require a class &amp; an interface when creating my generic object.</p> <p>I've created the simplest version of this that I can think of - hopefully that will explain my problem better than I can.</p> <pre><code>abstract class Base {} class Class1 : Base, IComparable&lt;Base&gt; { public int CompareTo(Base other) { return GetHashCode().CompareTo(other.GetHashCode()); } } class Class2 : Base, IComparable&lt;Base&gt; { public int CompareTo(Base other) { return GetHashCode().CompareTo(other.GetHashCode()); } } class Class3 : Base {} class Program { // This list should only accept objects that extend (Base &amp; IComparable&lt;Base&gt;) public static List&lt;Base&gt; BigList = new List&lt;Base&gt;(); static void Main(string[] args) { Class1 c1 = new Class1(); Class2 c2 = new Class2(); Class3 c3 = new Class3(); BigList.Add(c1); BigList.Add(c2); // This should not be allowed because Class3 does not extend IComparable&lt;Base&gt; BigList.Add(c3); Check(new Class1()); } public static void Check(Base bb) { foreach (Base b in BigList) { // Assert that this is true IComparable&lt;Base&gt; c = (IComparable&lt;Base&gt;)b; if (c.CompareTo(bb) &lt; 0) Console.WriteLine("Less Than"); else if (c.CompareTo(bb) == 0) Console.WriteLine("Equal"); else if (c.CompareTo(bb) &gt; 0) Console.WriteLine("Greater Than"); } } } </code></pre> <p>As you can see from the inline comments in the code, I'd like the list <code>BigList</code> to require that the objects being added extend <code>Base</code> <strong>AND</strong> implements <code>IComparable&lt;Base&gt;</code>. This isn't really multiple inheritance though because it's only one class (and an interface).</p> <p>Does anyone know of a way to do this?</p> <p><strong>EDIT</strong></p> <p>Thanks for the comments everyone. Basically the answers come in two flavors: Create an Intermediate class, or use <code>List&lt;IComparable&lt;Base&gt;&gt;</code>. #2 isn't an option because there is logic in Base that we do actually need. #1 is the most viable option, and the one that we are <em>grudgingly</em> going with. The concern with this approach is the amount of mess and complexity this will add in the actual class hierarchy.</p> <p>Regardless if C# won't let us do what we want to do then we will have to do it with the intermediate classes. Thanks everyone.</p>
 

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