Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IsAssignableFrom or AS?

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?

like image 591
abatishchev Avatar asked Aug 03 '10 12:08

abatishchev


People also ask

What is IsAssignableFrom?

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 vs IsAssignableFrom C#?

"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.

Is assignable from VS Instanceof?

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.

Is C# assignable?

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);


2 Answers

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.

like image 139
Davy8 Avatar answered Oct 03 '22 16:10

Davy8


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;
}
like image 42
Denis Palnitsky Avatar answered Oct 03 '22 15:10

Denis Palnitsky