zetar
zetar

Reputation: 1233

Correct way to change value of an item in a list of class objects

Given a class like so:

 public class Dinosaur
{
    public string Specie { get; set; }
    public int Age { get; set; }
    public int Weight { get; set; }
    public Point Location { get; set; }

    // Constructor
    public Dinosaur()
    {

    }

And a list like so:

        public static List<Dinosaur> Dinosaurs = new List<Dinosaur>();

What is the correct method to change a value in the last item in the list? This throws an error ("The best overloaded method match for 'System.Collections.Generic.List.this[int]' has some invalid arguments"):

Dinosaurs[Dinosaurs.Last()].Location.X = pixelMousePositionX;

As always, thanks in advance! Stackoverflow has been a lifesaver on this project.

Upvotes: 1

Views: 2049

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460158

Dinosaurs.Last() returns already the last item, so you don't need the indexer at all.

Dinosaurs.Last().Location.X = pixelMousePositionX;

Now it's throwing this error: Cannot modify the return value of 'DinosaurIsland.Dinosaur.Location' because it is not a variable

This is because the Point is a struct and not a reference type. So you have to create a new point.

Point oldLocation = Dinosaurs.Last().Location;
Dinosaurs.Last().Location = new Point { X = pixelMousePositionX, Y = oldLocation.Y };

Upvotes: 9

John Bustos
John Bustos

Reputation: 19564

Given the way you're doing it, you have to refer to the item by it's index:

Dinosaurs[Dinosaurs.Count - 1].Location.X = pixelMousePositionX;

OR just reference the object directly:

Dinosaurs.Last().Location.X = pixelMousePositionX;

Upvotes: 1

David M
David M

Reputation: 72880

Dinosaurs.Last() returns the last item, not its index, so this:

Dinosaurs.Last().Location.X = pixelMousePositionX;

If you want to do it by index, then this:

Dinosaurs[Dinosaurs.Count - 1].Location.X = pixelMousePositionX;

Upvotes: 5

Related Questions