Note that there are some explanatory texts on larger screens.

plurals
  1. POWhen should or shouldn't I be using generic type constraints?
    primarykey
    data
    text
    <p>I've got a base class:</p> <pre><code>public abstract class StuffBase { public abstract void DoSomething(); } </code></pre> <p>And two derived classes</p> <pre><code>public class Stuff1 : StuffBase { public void DoSomething() { Console.WriteLine("Stuff 1 did something cool!"); } public Stuff1() { Console.WriteLine("New stuff 1 reporting for duty!"); } } public class Stuff2 : StuffBase { public void DoSomething() { Console.WriteLine("Stuff 2 did something cool!"); } public Stuff1() { Console.WriteLine("New stuff 2 reporting for duty!"); } } </code></pre> <p>Okay, now say I've got a list of items:</p> <pre><code>var items = new List&lt;StuffBase&gt;(); items.Add(new Stuff1()); items.Add(new Stuff2()); </code></pre> <p>and I want them all to call their DoSomething() method. I could expect to just iterate the list and call their DoSomething() method, so let's say I've got a method to do that called AllDoSomething() that just iterates over the list and does the job:</p> <pre><code>public static void AllDoSomething(List&lt;StuffBase&gt; items) { items.ForEach(i =&gt; i.DoSomething()); } </code></pre> <p>What is the practical difference of the following method?</p> <pre><code>public static void AllDoSomething&lt;T&gt;(List&lt;T&gt; items) where T: StuffBase { items.ForEach(i =&gt; i.DoSomething()); } </code></pre> <p>Both methods appear in real terms, although being syntactically different, to be doing the same thing.</p> <p>Are they just different ways of doing the same thing? I understand generics and type constraints but can't see why I would use one way over the other in this instance.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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