The .Last() method for Lists only returns a value. I would like to be able to do something like this.
List<int> a = new List<int> { 1, 2, 3 };
a.Last() = 4;
This is my attempt at writing an extension method (it does not compile)
public unsafe static T* mylast<T>(this List<T> a)
{
return &a[a.Count - 1];
}
Is what I want to do possible?
edit:
This is an example of where I would want to use it.
shapes.last.links.last.points.last = cursor; //what I want the code to look like
//how I had to write it.
shapes[shapes.Count - 1].links[shapes[shapes.Count - 1].links.Count - 1].points[shapes[shapes.Count - 1].links[shapes[shapes.Count - 1].links.Count - 1].points.Count-1] = cursor;
This is why doing
shapes[shapes.Count-1]
isn’t really a solution.
I’d recommend Thom Smith’s solution, but if you’d really like to have property-like access, why not just use a property?
Used like:
No unsafe code, so it’s better. Also, it doesn’t preclude the use of LINQ’s
Lastmethod (the compiler can tell the two apart due to how they’re used).