C# Arraylist foreach

C# Arraylist foreach


   In this post we will add objects of different types into ArrayList. we will iterate this arraylist using foreachlist.

ArrayList will hold the Objects.

e.g. UserInfo object and ProductInfo object.
 

 

public class UserInfo

{

string _firstName; public string FirstName

{

get{return _firstName;}
set{_firstName = value;}

}

string _lastName;

public string LastName

{

get{return _lastName;}
set{_lastName = value;}

}

}

public class ProductInfo

{

string _productName;

public
string ProductName

{

get{return _productName;}
set{_productName = value;}

}

}


Iterate using forwach loop

protected void Button1_Click(object sender, EventArgs e)

{

ArrayList arrLst = new ArrayList();

// Add UserInfo object into array list

UserInfo u1 = new UserInfo();

u1.FirstName = "Satalaj";
u1.LastName =
"More";

arrLst.Add(u1);

UserInfo u2 = new UserInfo();

u2.FirstName = "Mike";
u2.LastName =
"Marco";

arrLst.Add(u2);

//Add ProductInfo object into array list

ProductInfo p1 = new ProductInfo();

p1.ProductName = "Samsung";

arrLst.Add(p1);

ProductInfo p2 = new ProductInfo();
p2.ProductName =
"Nokia";

arrLst.Add(p2);

foreach(object o in arrLst)

{

try

{

// lets iterate objects in arraylist and get their type / member info

// I have applied try catch block here bcoz you can see

// arrays are not type safe

System.Type type = o.GetType();string str = type.Name ;

 

Response.Write(str);

Response.Write("<Br />");

}

catch(Exception ex)

{

Response.Write(ex.Message);

}

}

}

Tags:

C# foreach loopC# Arraylist foreachC# ArrayList Search using Linq Extension OfType MethodC# Listbox ForeachC# Regular Expression Get Text Between Bracketsc# stringC# Break StatementC# looping through arrayC# DateTime DifferenceC# XML XmlReaderC# Binary To String

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.