Click here to Skip to main content
15,885,244 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi everyone,The question is that is it right to use "GetRange" method to add new cards to player1 ' s arrayList?

C#
ArrayList cards = new ArrayList();
// i also create cards arrayList with "for".

ArrayList player1 = new ArrayList();
Random rnd = new Random();

for (int i = 0; i < 5; i++)
{
  int card = rnd.Next(0, cards.Count);
  player1.Add(cards.GetRange(card, 1))
  cards.RemoveAt(card);
}
Posted
Updated 24-Jan-12 3:07am
v2

If you are only getting one item, I don't think GetRange is a good use. I would use it more for when you need to get more than one item.

I would just use:

player1.Add(cards[card]);
 
Share this answer
 
Comments
LanFanNinja 24-Jan-12 9:43am    
+5 I would do the same.
Member 8592678 24-Jan-12 9:49am    
but when i want to add multiple items can i use it?
Tim Groven 24-Jan-12 9:53am    
Absolutely. Just remember, it returns a sequential range. :)
It is syntactically correct (because a Add method accepts an object and an ArrayList, the return value of GetRange, is an object) but probably is NOT what you want to do, try instead:
C#
player1.Add(cards[card]));


This 'ambiguity' is a strong point in favour of strong typed collections ( :-) ), that is generic collections.
 
Share this answer
 
Comments
LanFanNinja 24-Jan-12 9:43am    
+5 I agree.
will work but there are certainly clearer ways to do this. One recommendation I have for you is to change from an ArrayList to a generic List<int> and then just index the List to retrieve your value.

i.e. something like the following

C#
List<int> cards = new List<int>();
List<int> player1 = new List<int>();
Random rnd = new Random();
for (int i = 0; i < 5; i++)
{
    int card = rnd.Next(0, cards.Count);
    player1.Add(cards[card]);
    cards.RemoveAt(card);
}
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900