While I don't quite understand why C# doesn't provide collection methods that remove AND return elements in one command I try to write my own custom extensions ...
public static T RemoveLast<T>(this List<T> list)
{
if (list.Count > 0)
{
var item = list[list.Count - 1];
list.RemoveAt(list.Count - 1);
return item;
}
return null;
}
However this gives an error for the return line: Cannot convert expression type 'null' to return type 'T'.
But trying to set T
to be nullable (T?
) isn't possible either. How do I change this so that T can be nullable?