Ricardinho
Ricardinho

Reputation: 53

How to get objects of specific type from a List of objects

I have a collection which stores multiple object types, a Textbox and a Textblock, which i am declaring like this:

List<object> textBoxCollection= new List<object>();

However, when i run a foreach loop looking just for the Textbox object, it throws an invalidcastexception. My assuption of the foreach loop is that it would only run the operation on the object type i have called out. Where am i going wrong? Heres my loop:

foreach (MyTextBox mtb in textBoxCollection)
{

    int number
    bool mybool = Int32.TryParse(mtb.Text, out number);

    if (mybool == false)
    {
        //some operation
    }
    else
    {
        //some other operation
    }
} 

Upvotes: 1

Views: 92

Answers (2)

Viktor S.
Viktor S.

Reputation: 12815

You can check object type using is statement:

    foreach (object tmp in textBoxCollection)
    {

        if(tmp  is MyTextBox) {
           MyTextBox mtb = (MyTextBox )tmp;
           int number
           bool mybool = Int32.TryParse(mtb.Text, out number);

           if (mybool == false)
           {
              //some operation
           }
           else
           {

              //some other operation
           }
        }
     } 

Or similar statement as:

    foreach (object tmp in textBoxCollection)
    {
        MyTextBox mtb = tmp as MyTextBox;
        if(mtb != null) {
        .......
        }
    }

Upvotes: 1

Jamiec
Jamiec

Reputation: 136124

You need to narrow down the enumeration to only the correct type using OfType<T>()

foreach (MyTextBox mtb in textBoxCollection.OfType<MyTextBox>())
{ ... }

Upvotes: 11

Related Questions