Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "is" and "IsAssignableFrom" C# [duplicate]

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;
}
like image 957
Haighstrom Avatar asked Jul 18 '13 14:07

Haighstrom


1 Answers

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?"

like image 102
Eric Lippert Avatar answered Sep 21 '22 00:09

Eric Lippert