2

I wonder if there is a equivalent c++ vector::back in c#. c++ vector::back is the function returns a reference to the last element of the vector. Thank you.

galaxyan
  • 5,944
  • 2
  • 19
  • 43

1 Answers1

4

Yeap, the corresponding structure in C# is the List<T>. You can get the last element simply writing this:

list.Last();

where list is a List<T>

UPDATE

One thing that we should point out is the fact that, if the list is empty, we will get an InvalidOperationException.

For this reason it's may better to use the LastOrDefault method. So your call will be change to the following one:

list.LastOrDefault();

So for instance if list is a List<int> and it is empty, then list.LastOrDefault() will be 0, where 0 is the default value for an int.

For further documentation please refer here.

Christos
  • 53,228
  • 8
  • 76
  • 108
  • Which actually works for any `IEnumerable(Of T)` which is pretty cool - just remember to add `using System.Linq` to your namespace imports. – RB. Mar 26 '14 at 14:53
  • Mind that this is not a reference in C#. I.e. a `List` will not allow you to change the last member. – Onur Mar 26 '14 at 15:09