I have next code:
private T CreateInstance<T>(object obj) // where T : ISomeInterface, class
{
...
if (!typeof(T).IsAssignableFrom(obj.GetType())) { throw ..; }
return (T)obj;
}
Can it be replaced with this:
T result = obj as T;
if (result == null) { throw ..; }
return result;
If not - why?
isAssignableFrom() determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.
"Is" operator allows you to check if particular instance is of particular type or inherits this type wheras IsAssignableFrom allows you to check if a Type is castable to another Type. Then you must use IsAssignableFrom.
In other words, instanceof operator checks if the left object is same or subclass of right class, while isAssignableFrom checks if we can assign object of the parameter class (from) to the reference of the class on which the method is called.
IsAssignableFrom(Type) Method is used determine whether an instance of a specified type can be assigned to a variable of the current type. Syntax: public virtual bool IsAssignableFrom (Type c);
What about if (!(bar is T)) { throw ..; }
Alternatively if you don't need your own exception message the simplest answer is just to do:
return (T)obj;
The reason if that if it's not castable an InvalidCastException will be thrown and the return ignored. Unless you're adding some more logic or a custom error message there's no need to do a check and throw your own exception.
Another variant:
private T CreateInstance<T>(object obj) where T : ISomeInterface // as OP mentioned above
{
...
T result = obj as T;
if (result == null)
{ throw ..; }
else
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With