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
Post a Comment