Difference between "is" and "IsAssignableFrom" C #

What's the difference between:

typeof(IInterface).IsAssignableFrom(typeof(Class)); 

and

 typeof(Class) is IInterface 

?

Edit: for context, my function looks 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; } 
+4
source share
3 answers

They are similar, but conceptually very different. The first answers the question "if I had a variable of this type, can I assign it a value of this type?"

The latter answers the question "can this actual value be converted to this type by reference or box conversion?"

In the latter case, the actual object is an object of type Type , and 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; 

First query: "Can a Type be converted to an interface?" and the second one asks: "Can a Class object be converted to an interface?"

+13
source

typeof(Class) is IInterface will always evaluate to false since typeof(Class) is equal to RuntimeType . The correct way to use is an instance of this class, for example

 Class c = // something bool isIt = c is IInterface; 

is should be used when you want to find out if a value is convertible for a type that is known at compile time.

IsAssignableFrom should be used when one or both types are known only at run time. For instance. someType.IsAssignableFrom(someOtherType) . If both types are known at compile time, for example. typeof(IInterface).IsAssignableFrom(typeof(Class)); , you can find out the answer by looking at the Class definition, and it really doesn't make sense to check it at runtime.

+1
source

Some differences:

A: with IsAssignableFrom you do not need any object instances (only System.Type objects), which is very useful for reflection.

B: With a keyword get some compile-time hints if the types are always / never compatible (at least with resharper)

C: These are kind of opposites. IsAssignableFrom checks if an object of the type passed as an argument can have a variable of another type. Keyword checks if the object on the left side of the keyword can be assigned to a type variable to the right of the keyword.

0
source

Source: https://habr.com/ru/post/1492107/


All Articles