1

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?

BadmintonCat
  • 9,416
  • 14
  • 78
  • 129

2 Answers2

1

There might be different solutions to your problem. One single solution cant solve your problem

lets discuss solutions scenario wise which suits to your requirment

Scenario 1: If you want to return last element and if last element not present then you want to return default value of that datatype, then you can use return default(T);

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 default(T);
        }

Scenario 2: If you want to make this function only for value type then you can make return value Nullable like below

public static Nullable<T> RemoveLast<T>(this List<T> list) where T:struct
        {
            if (list.Count > 0)
            {
                var item = list[list.Count - 1];
                list.RemoveAt(list.Count - 1);
                return (T)item;
            }
            return null;
        }

Here specifying T type is struct is needed since reference types are by default nullable and making them nullable not making any sense to compiler so compiler wont allow it

Rajiv
  • 1,245
  • 14
  • 28
0

NVM, got it:

return default(T);
BadmintonCat
  • 9,416
  • 14
  • 78
  • 129
  • 1
    But this scenario will fail if T is integer as it will return 0 .. so it will be difficult to find, is it real value or default value (0)........ this depends on how you are using this function. if this case doesn't affect your solution then it is nice solution – Rajiv Feb 23 '19 at 15:04