Another type of return from a method in a generic class

The following code has just been compiled, is this possible 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();
    }
}
+3
source share
2 answers

Your desire is my team.

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 to reduce grip, you can go with:

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

A method that ends with an automaticlyDetectedReturnTypeOfEitherAOrB () call should know the return type, though. If you do not make the method return an object. Then the calling method can return everything (int or string) and find out what to do with it.

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

R GetStuff<R>(T theObject)
{
    return (R)theObject.DoStuff();
}

void Method1()
{
    int i = GetStuff<int>(new A());
    string s = GetStuff<string>(new B());
}
+2
source

Source: https://habr.com/ru/post/1710281/


All Articles