Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I overload a C# method by specific instances of a generic type
    text
    copied!<p>Coming from a C++ background, I've run into a snag with overloading based on a specific instance of a generic type. The following doesn't work since only once instance of the code for the <code>Foo&lt;T&gt;</code> class is ever generated, so inside the <code>Method</code>, the type of <code>this</code> is simply <code>Foo&lt;T&gt;</code>, not <code>Foo&lt;A&gt;</code> or <code>Foo&lt;B&gt;</code> as I'd hoped. In C++ I'm used to templates being instantiated as unique types.</p> <pre><code>using System.Collections.Generic; class A { // Concrete class } class B { // Concrete class } class Bar { public void OverloadedMethod(Foo&lt;A&gt; a) {} // do some A related stuff public void OverloadedMethod(Foo&lt;B&gt; b) {} // do some B related stuff public void OverloadedMethod(OtherFoo of) {} // do some other stuff public void VisitFoo(FooBase fb) { fb.Method(this); } } abstract class FooBase { public abstract void Method(Bar b); } class Foo&lt;T&gt; : FooBase { // Class that deals with As and Bs in an identical fashion. public override void Method(Bar b) { // Doesn't compile here b.OverloadedMethod(this); } } class OtherFoo : FooBase { public override void Method(Bar b) { b.OverloadedMethod(this); } } class Program { static void Main(string[] args) { List&lt;FooBase&gt; ListOfFoos = new List&lt;FooBase&gt;(); ListOfFoos.Add(new OtherFoo()); ListOfFoos.Add(new Foo&lt;A&gt;()); ListOfFoos.Add(new Foo&lt;B&gt;()); Bar b = new Bar(); foreach (FooBase fb in ListOfFoos) b.VisitFoo(fb); // Hopefully call each of the Bar::Overloaded methods } } </code></pre> <p>Is there a way to get something like this to work in C#? I'd rather not have to duplicate the code in Foo as separate classes for every type I want to use it for.</p> <p>Edit: Hopefully this is a little clearer.</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