I have a pair of classes. These are 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 so that I could use PageResult.Create(5, listOf5Items) as opposed to any other lengthier syntax. I didn't put the Create method in the PageResult(T) class because I'm pretty sure that requires me to type PageResult<int>(5, listOf5Numbers) instead, and that's an extra five characters...
But having two classes for it seems pretty lame. Is there a way I can get the more compact syntax without having a throwaway class just to store it?
As you already noted, you'd have to specify type parameters to even access the Create function, because that specific PageResult<T> class won't even exist until the JIT creates it when a method starts calling it. See Tuples for an instance of the .NET Framework itself doing just this pattern for the basically the same reason.
Note that another option is to make the PageResult class non-static, and inherit PageResult<T> : PageResult which will allow you to store a collection of PageResult objects without a type parameter. This can also be useful if you use an abstract PageResult
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With