views:

95

answers:

2

This is the definition:

public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source);

How to replace TResult with something like:

Type.GetType("MyClass from assembly");
+3  A: 

You can't. Generic arguments enforce type security at compile time while the Type.GetType uses reflection and is not known at compile time. What exactly are you trying to achieve?

Darin Dimitrov
Does it mean that I have to iterate through the collection manually and look at their types with typeof ?
PaN1C_Showt1Me
You can't use `typeof` because it expects you to pass a value which is known at compile time. You could probably use a non strongly typed collection but once again, what are you trying to do? You talk about iterating over a collection. What collection? Give some more details.
Darin Dimitrov
I'm trying to do ISite.Container.Components.OfType<A>().First<A>() .. and A resides in another project / assembly. And I cannot add reference to that project.
PaN1C_Showt1Me
+3  A: 

You can't do this at compile time if you don't know the type involved, but you could write your own extension method for IEnumerable:

public static IEnumerable OfType(this IEnumerable source, Type t)
{
    foreach(object o in source)
    {
        if(t.IsAssignableFrom(o.GetType()))
            yield return o;
    }
}
Lee