Jump to content

View more

Image of the Day

雑魚は多めにして、爽快感重視にしつつ・・・(´・ω・`)
早いとこ、ベースを作って、完成にもっていかないとね。
タイトルもまだ迷ってるだよなぁ。 
#indiedev  #indiegame #screenshotsaturday https://t.co/IwVbswGrhe
IOTD | Top Screenshots

The latest, straight to your Inbox.

Subscribe to GameDev.net Direct to receive the latest updates and exclusive content.


Sign up now

C# - Accessing last element in a List.

4: Adsense

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   

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

#2 cyansoft   Members   

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   

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.