tags:

views:

532

answers:

2

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();
    }
}
A: 

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());
}
rally25rs
+2  A: 

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()
  }
}
David B
Thanks. A bit verbose but gets the job done. :)
I know what T means, but where did U come from? Are there other letters that I don't know about that mean something?
jasonh
jasonh, generics can have any letter
@aoooa: What happens if I have a class U?
jasonh
T is typically the name assigned to the first "type parameter". You get to choose the name of "type parameters" and can choose U or Bob if you like.
David B
So it's really up to me to decide the name of the generic type. T is just a convention?
jasonh
Yup. you didn't know that?
RCIX