Jump to content
  • Advertisement
Sign in to follow this  
chadsxe

C# - Accessing last element in a List.

This topic is 3352 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I have a question about accessing the last element in a list. I am entering a function and creating a new sprite object which is stored into a List. I then need to access the sprite object I just added so I can further do work on it. I am stumped on how to make sure I access what I just added.
                // A collection of sprite objects
        private List<Sprite> sprites;
        public void AddNewSprite(string filePath)
        {
            sprites.Add(new Sprite(this,appReference.GetContentManager()));
            //I need to acces the element I just added so I can all the following function on it
            //sprite.LoadSprite(filePath); 
        }
Any help would be great. Regards Chad

Share this post


Link to post
Share on other sites
Advertisement

// A collection of sprite objects
private List<Sprite> sprites;
public void AddNewSprite(string filePath)
{
sprites.Add( new Sprite(this,appReference.GetContentManager()));
Sprite sprite = sprites[sprites.Count-1];
sprite.LoadSprite(filePath);
}

Share this post


Link to post
Share on other sites
There's no need to get the last element if you just write code that is a bit more explicit and readable...

public void AddNewSprite(string filePath)
{
Sprite newSprite = new Sprite(this,appReference.GetContentManager());
sprites.Add(newSprite);

newSprite.Load(filePath);
}



But, if you must get the last element you can do as mentioned above by Cyansoft, or if you are including System.Linq:

sprites.Last().LoadSprite(filePath);

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!