C# Generic return type

Hey guys,

I want to get the last element in a List. I’m aware you can do List[List-1] but I’m needing to do this a lot and it looks ugly, especially when it is nested:

List<A> list1 = new List<A>();


//A has a data member of type List<B> lets call it list2

//
//add some things to both lists
//

list1[list1.Count-1].list2[List1[list1.Count-1].list2.Count-1].something = somethingElse

Anyway, I want to write a generic method which takes in a list and returns the last element in the List.

I’m aware that List has an extension method, Last(), which does this but I can’t work out how to access it, possibly unity does not allow you to do this (http://forum.unity3d.com/threads/70804-C-Extension-Methods)?

I need the return type to be generic but i can’t work out how to declare it as such:

public static T /* maybe <T>??*/ getLastListEntry(List<T> list){
    return list[list.Count-1];
}

I hope that shows what I am trying to do, hopefully someone can help.

Thanks guys.

Use Linq:

 using System.Linq;

 var item = someList.Last();

Write it yourself:

  public static class ListHelpers
  {
        public static T LastItem<T>(this List<T> list)
        {
              return list[list.Count-1];
        }
  }

  var item = someList.LastItem();