How to use Generic interface with two type in return of method

212 Views Asked by At

I need to create an interface with 2 type and use it as a method return value.

public interface StringLong<T1,T2>
where T1 : string
where T2 : long
{}

StringLong<T1,T2> method StringLong<T1,T2>()
2

There are 2 best solutions below

0
On

It makes no sense to define an interface with two generic types that you constrain to just string and long.

It sounds like you just want a tuple:

(string, long) MyMethod()
{
    return ("Hello", 42L);
}

You can even name the return values:

(string message, long meaningOfLife) MyMethod()
{
    return ("Hello", 42L);
}

Then you can write:

var result = MyMethod();
Console.WriteLine(result.message);
Console.WriteLine(result.meaningOfLife);
0
On

I think is the functionality you are trying to achieve (from the comments). Since the return might be of either string or long there common ancestor is object.

Once you have the value you can use pattern matching to cast the result into the appropriate type:

static class Program
{
    static void Main(string[] args)
    {
        var obj = MethodReturnsStringOrLong(1722);
        switch (obj)
        {
            case string str:
                Console.WriteLine($"String is {str}");
                break;
            case long lng:
                Console.WriteLine($"Long is {lng}");
                break;
            default:
                throw new NotSupportedException();
        }
    }

    public static object MethodReturnsStringOrLong(int input)
    {
        if (input % 2 == 0)
        {
            return 1928374028203384L;
        }
        else
        {
            return "ASIDJMFHSOASKSJHD";
        }
    }
}

An alternative is the create your own common ancestor, like the class Value below that might contains either a long and/or a string.

public class Value
{
    public Value(long longValue)
    {
        LongValue = longValue;            
    }
    public Value(string stringValue)
    {
        StringValue = stringValue;
    }

    public long? LongValue { get; }
    public string StringValue { get; }
}


static class Program
{
    static void Main(string[] args)
    {
        var obj = MethodReturnsStringOrLong(1722);
        if (obj.LongValue.HasValue)
        {
            Console.WriteLine($"Long is {obj.LongValue.Value}");
        }
        if (!string.IsNullOrEmpty(obj.StringValue))
        {
            Console.WriteLine($"String is {obj.StringValue}");
        }
    }

    public static Value MethodReturnsStringOrLong(int input)
    {
        if (input % 2 == 0)
        {
            return new Value(1928374028203384L);
        }
        else
        {
            return new Value("ASIDJMFHSOASKSJHD");
        }
    }

}