c# - IsAssignableFrom, IsInstanceOfType and the is keyword, what is the difference? -


i have extension method safe casting objects, looks this:

public static t safecastas<t>(this object obj) {     if (obj == null)         return default(t);      // 1 should use?      // 1. isassignablefrom     if (typeof(t).isassignablefrom(obj.gettype()))         return (t)obj;      // 2. isinstanceoftype     if (typeof(t).isinstanceoftype(obj))         return (t) obj;      // 3. operator     if (obj t)         return (t) obj;      return default(t); } 

as can see, have 3 choice, 1 should use? difference between isassignablefrom, isinstanceoftype, , is operator?

you use whatever have information for.

if have instance , static type want check against, use is.

if don't have static type, have type object, have instance want check, use isinstanceoftype.

if don't have instance , want check compatibility between theoretical instance of type , type, use isassignablefrom.

but seems re-implementing as operator (except yours work non-nullable value types, not big limitation).


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -