Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static class/method this and generics

So I have a certain method I want to call on a List (it's a generic method that I run every time in different files, so I would like to put it in a static class).

The method is this:

public static List<Item> GetRangeOrMax(this List<Item> list, int amount)
        {
            return list.Count < amount ? list.GetRange(0, list.Count) : list.GetRange(0, amount);
        }

The problem is that not every list I need to run this on is of the type Item. I was wondering if I would be able to solve this using generics? Say something along the lines of (this List<T> list ...

The problem here being that the method must also return that value and I would like to keep using the this keyword. If not possible I guess I'll have to make the method with a different overloader for each type.

like image 814
Fverswijver Avatar asked Jul 08 '26 04:07

Fverswijver


1 Answers

You can use a generic extension method.

static List<T> GetRangeOrMax<T>(this List<T> list, int amount)        
{            
      return list.Count < amount ? list.GetRange(0, list.Count) : list.GetRange(0, amount);        
}
like image 75
Bas Avatar answered Jul 10 '26 17:07

Bas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!