Compact syntax for static Create () method for generic class?

I have a couple of classes. They literally copy / paste from my project:

public static class PageResult
{
    public static PageResult<T> Create<T>(int totalCount, IList<T> items)
    {
        return new PageResult<T>()
        {
            TotalCount = totalCount,
            Items = items,
        };
    }
}

public class PageResult<T>
{
    public int TotalCount { get; set; }
    public IList<T> Items { get; set; }
}

      

The reason I did this is to use PageResult.Create(5, listOf5Items)

as opposed to any other longer syntax. I didn't put the Create method in the class PageResult(T)

because I'm sure it requires me to type PageResult<int>(5, listOf5Numbers)

instead, and that an extra five characters ...

But having two classes for this seems pretty lame. Is there a way to get more compact syntax without having a throwaway class to keep it?

+3


source to share


2 answers


As you already noted, you will need to specify the type parameters to even access the function Create

, because this special class PageResult<T>

doesn't even exist until the JIT creates it when the method starts calling it. See Tuples for an instance of the .NET Framework that does this exact template for the same reason.



Note that another option is to make the class PageResult

not static

and inherit PageResult<T> : PageResult

, which will allow you to store a collection of objects PageResult

without a type parameter. It can also be helpful if you are usingabstract PageResult

+2


source


Not. You could create a VS snippet (or some other plugin / tool that could generate source code) to print any of the templates for you, but eventually that code should be there.



+1


source







All Articles