Tutorial :different return type from method in generic class


The following code is just made up, is this possible to do with C#?

class A  {      public int DoStuff()      {          return 0;      }  }    class B  {      public string DoStuff()      {          return "";      }  }    class MyMagicGenericContainer<T> where T : A, B  {      //Below is the magic <------------------------------------------------      automaticlyDetectedReturnTypeOfEitherAOrB GetStuff(T theObject)      {          return theObject.DoStuff();      }  }  


Your wish is my command.

public interface IDoesStuff<T>  {    T DoStuff();  }    public class A : IDoesStuff<int>  {    public int DoStuff()    {  return 0; }  }    public class B : IDoesStuff<string>  {    public string DoStuff()    { return ""; }  }  public class MyMagicContainer<T, U> where T : IDoesStuff<U>  {    U GetStuff(T theObject)    {      return theObject.DoStuff();    }  }  

If you want less coupling, you could go with:

public class MyMagicContainer<U>  {    U GetStuff(Func<U> theFunc)    {      return theFunc()    }  }  


The method that ends up calling automaticlyDetectedReturnTypeOfEitherAOrB() would have to know the return type though. Unless you make the method return object. Then the calling method can get back whatever (int or string) and figure out what to do with it.

Another option is to do something like this: (sorry, I don't have VisStudio open to validate syntax or that it works right)

R GetStuff<R>(T theObject)  {      return (R)theObject.DoStuff();  }    void Method1()  {      int i = GetStuff<int>(new A());      string s = GetStuff<string>(new B());  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »