MorkaLork Development

Interesting stuff I've picked up over the years...

Return list<>

2009-04-17 07:19:46 | 166 views | csharp class method tutorial list return value object

A misc apart...



Right, I'm just writing this down not to forget it:
If you want to use a method in another class to fill a list for you and send it back, this is how you do it. I'm showing an example on how to easily create a deck-of-cards-list<T>.

Cards.cs




public class Cards
{
public string color;
public int number;

public Cards(string color, int number)
{
this.color = color;
this.number = number;
}
}



ListUtils.cs




public class ListUtils
{
public ListUtils()
{
}

public List<Cards> populateDeck()
{
List<Cards> lst = new List<Cards>();
string[] colors = new string[]{"Hearts", "Spade", "Clove", "Diamond"};

for (int j=0;j <4 ;j++ ) {

for (int i=2;i<15 ;i++ ) {
lst.Add(new Cards(colors[j], i));
}

}

return lst;
}

}


MainForm.cs




public partial class MainForm : Form
{
public MainForm()
{

InitializeComponent();


}

void MainFormLoad(object sender, EventArgs e)
{
ListUtils LU = new ListUtils();
List<Cards> myList = LU.populateDeck();


myList.ForEach(delegate(Cards Cs)
{
lsbIndex1.Items.Add(Cs.color + " " + Cs.number);
});
}
}


Allright, so what we do here is create three files:


The Cards.cs file contains only the Cards class that we use in our list

The ListUtils.cs contains the populateDeck() method that is the core of this article. It creates a deck by nested loops. We have one BIG loop that loops four times through an array we've made containing the four colors of the deck. Inside that loop, for every color, we loop 13 times to obtain the 2-14 numbers for every color.
When it's done we simply return the list.

The MainForm.cs contains the code that calls and collects the list. This code is important:


ListUtils LU = new ListUtils();
List<Cards> myList = LU.populateDeck();


We collect the whole list at the same time as we declare the list.


Well, that's it.



Article comments

Feel free to comment this article using a facebook profile.

I'm using facebook accounts for identification since even akismet couldn't handle all the spam I receive every day.