Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Is Type in list question

Tags:

c#

generics

Basic c# question. In the sample bellow But the 'is' doesn't like the type variable. Any ideas there should be a simple answer.

    List<object> list = new List<object>();
    list.Add("one");
    list.Add(2);
    list.Add('3');

    Type desiredType = typeof(System.Int32);

    if (list.Any(w => w is desiredType))
    {
        //do something
    }
like image 825
Ryan Mrachek Avatar asked Apr 27 '11 11:04

Ryan Mrachek


2 Answers

Try this:

List<object> list = new List<object>();
list.Add("one");
list.Add(2);
list.Add('3');

Type desiredType = typeof(System.Int32);

if (list.Any(w => w.GetType().IsAssignableFrom(desiredType)))
{
    //do something
}

Anyway: are you sure you want to create a list of objects?

like image 193
as-cii Avatar answered Oct 18 '22 18:10

as-cii


w.GetType() == desiredType.

Why are you abusing generics like that?

like image 4
Femaref Avatar answered Oct 18 '22 18:10

Femaref