Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic T from parameters instead of manually specifying

Tags:

c#

generics

I wrote this class:

public class ResultsPair<T>
{
    public T Value { get; set; }
    public ResultsItem Result { get; set; }

    public ResultsPair(ResultsItem result, T value)
    {
        Result = result;
        Value = value;
    }

    public static ResultsPair<T> Create(ResultsItem result, T value)
    {
        return new ResultsPair<T>(result, value);
    }

    public static ResultsPair<T> CreateSuccess(T value) => Create(ResultsItem.Success(string.Empty), value);
    public static ResultsPair<T> CreateError(ResultsItem result) => Create(result, default(T));
}

To call it, I would do these:

ResultsPair<User>.CreateSuccess(newUser);
ResultsPair<User>.CreateError(ResultsItem.Error("A server connection error has occured."));

On the first one, newUser is type User, so I do not want to manually define it again using < User >.

On the CreateError, I have no problem defining manually the T class, since it won't know it by default.

On just the Create method, I need to do this ResultsPair<User>.Create(ResultsItem, User). Which I don't like. ResultsPair.Create(ResultsItem, User) should be enough.

Is there a way to have it achieve what I want?

Thanks

like image 200
FerX32 Avatar asked Dec 08 '25 08:12

FerX32


1 Answers

You can achieve this by additionally creating a non-generic class ResultsPair with generic methods Create, CreateSuccess and CreateError:

public static class ResultsPair
{
    public static ResultsPair<T> CreateSuccess<T>(T value) => Create(ResultsItem.Success(string.Empty), value);
    public static ResultsPair<T> CreateError<T>(ResultsItem result) => Create(result, default(T));

    public static ResultsPair<T> Create<T>(ResultsItem result, T value)
    {
        return new ResultsPair<T>(result, value);
    }
}

Usage:

ResultsPair.CreateSuccess(newUser);
ResultsPair.CreateError<User>(ResultsItem.Error("A server connection error has occured."));
ResultsPair.Create(ResultsItem, User)

Just to clarify: Your complete code would look like this:

public class ResultsPair<T>
{
    public T Value { get; set; }
    public ResultsItem Result { get; set; }

    public ResultsPair(ResultsItem result, T value)
    {
        Result = result;
        Value = value;
    }
}

public static class ResultsPair
{
    public static ResultsPair<T> CreateSuccess<T>(T value) => Create(ResultsItem.Success(string.Empty), value);
    public static ResultsPair<T> CreateError<T>(ResultsItem result) => Create(result, default(T));

    public static ResultsPair<T> Create<T>(ResultsItem result, T value)
    {
        return new ResultsPair<T>(result, value);
    }
}
like image 58
Daniel Hilgarth Avatar answered Dec 09 '25 22:12

Daniel Hilgarth