5

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
    }
2
  • 1
    Putting heterogeneous data in a list is asking for trouble, btw... Commented Apr 27, 2011 at 12:01
  • 1
    That's a nasty way to use generics, but I guess it's for demonstration only. Commented Apr 27, 2011 at 12:03

5 Answers 5

6

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?

Sign up to request clarification or add additional context in comments.

Comments

4

w.GetType() == desiredType.

Why are you abusing generics like that?

3 Comments

Note that type equality isn't quite the same as is; subclasses etc will be confusing...
Thank you.. IRL our app has a dozen panel types in a collection and wanted a generic way to determine if a panel of a particular type is already open.
Actually, AS-CII's answer should be closer to is behavior.
3

You could use the Linq extension method OfType:

list.OfType<> will return an IEnumerable to any items of the specified type.

1 Comment

This is what you want 9 times out of 10. The other 1/10 time the type isn't known at compile time (ie it's passed as a parameter rather than type parameter of a generic method), in which case you should use AS-CII's method. But usually OfType is what you want. Additionally OfType saves you the cast when you want to retrieve the values, which is handy.
1

If I recall correctly you have to write w is System.Int32..

Comments

1

The delegate is expecting a type or a namespace, but you're supplying a type instance. Try this:

if (list.Any(w => w is Int32))
{
    //do something
}

1 Comment

How was that "the point"? Your initial question stated that 'is doesn't like the type variable', and that there should be a simple answer. Saying w is Int32 is a lot simpler than getting a type instance and writing if (list.Any(w => w.GetType().IsAssignableFrom(desiredType)))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.