LikeToDo
LikeToDo

Reputation: 319

Generics without a specific type

I have this:

class Program
    {
        static void Main(string[] args)
        {

            var result = new Result<int, bool> { success = true, Data = 88 };
            var result2 = new Result<string, bool> { success = true, Data = "Niels" };


            Console.WriteLine(result2.success);
            Console.WriteLine(result2.Data);

            Console.ReadKey();
        }
    }

    public class Result<T, TU>
    {
        public TU success { get; set; }
        public T Data { get; set; }


    }

So this is a simple generic class with two properties.

I was just wondering, how to make this:

var result = new Result<int, bool> { success = true, Data = 88 };

even more generic :). Because you still have to "say" what the return type will be: <int, bool>

So is it possible to do it for example like this:

<T var1, T var2> ?

Thank you

So I mean like this:

var result = new Result<T var1, T var2> { success = true, Data = 88 };

So that you can fill in for success and for Data whatever you want(string, int , float, bool)..

Upvotes: 0

Views: 97

Answers (2)

grek40
grek40

Reputation: 13448

You can use a factory method to resolve the types automatically from the given parameters:

public static class ResultFactory
{
    public static Result<T, TU> Create<T, TU>(TU success, T data)
    {
        return new Result<T, TU> { success = success, Data = data };
    }
}

var result = ResultFactory.Create(true, 88);
var result2 = ResultFactory.Create(true, "Niels");

Upvotes: 6

Rahul
Rahul

Reputation: 77876

Because you still have to "say" what the return type will be: <int, bool>

Yes you will have to specify the type T,TU and can't keep the type open. Types must be closed at compile time. Thus calling it like <T var1, T var2> won't be possible unless it's wrapped inside another generic type or method

Upvotes: 0

Related Questions