I have an extension method to safe casting objects, that looks like this:
public static T SafeCastAs<T>(this object obj) {
if (obj == null)
return default(T);
// which one I should use?
// 1. IsAssignableFrom
if (typeof(T).IsAssignableFrom(obj.GetType()))
return (T)obj;
// 2. IsInstanceOfType
if (typeof(T).IsInstanceOfType(obj))
return (T) obj;
// 3. is operator
if (obj is T)
return (T) obj;
return default(T);
}
As you can see, I have 3 choice, so which one I should to use? Actually what is the difference between IsAssignableFrom
, IsInstanceOfType
, and is
operator?