What's the difference between:
typeof(IInterface).IsAssignableFrom(typeof(Class));
and
typeof(Class) is IInterface
?
Edit: for context, my function is something like this:
public static List<T> GetAllInstancesOfType<T>() where T:Entity
{
List<T> l = new List<T>();
if (typeof(IMyInterface).IsAssignableFrom(typeof(T)) //or (typeof(T) is IMyInterface)
foreach(Entity e in List1) if (e is T) l.Add(e as T);
else foreach (Entity e in List2) if (e is T) l.Add(e as T);
return l;
}
They are similar-looking but conceptually very different. The former answers the question "if I had a variable of this type, could I assign to it a value of that type?"
The latter answers the question "can this actual value be converted to this type via reference or boxing conversion?"
In the latter case, the actual object is an object of type Type
, not an object of type Class
. Make sure you understand the difference between:
Type t = typeof(Class);
Class c = new Class();
bool b1 = t is IInterface;
bool b2 = c is IInterface;
The first asks "can the Type
object be converted to the interface?" and the second asks "can the Class
object be converted to the interface?"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With