Jump to content

  • Log In with Google      Sign In   
  • Create Account

We're offering banner ads on our site from just $5!

1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


C# - Accessing last element in a List.


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
2 replies to this topic

#1 chadsxe   Members   -  Reputation: 146

Like
0Likes
Like

Posted 12 October 2009 - 11:52 AM

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

Sponsor:

#2 cyansoft   Members   -  Reputation: 307

Like
0Likes
Like

Posted 12 October 2009 - 12:04 PM


// 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);
}



#3 smitty1276   Members   -  Reputation: 560

Like
0Likes
Like

Posted 12 October 2009 - 12:27 PM

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);






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS