Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "as T" get an error but casting with (T) not get an error?

Why can I do this:

public T GetMainContentItem<T>(string moduleKey, string itemKey)
{
    return (T)GetMainContentItem(moduleKey, itemKey);
}

but not this:

public T GetMainContentItem<T>(string moduleKey, string itemKey)
{
    return GetMainContentItem(moduleKey, itemKey) as T;
}

It complains that I haven't restricted the generic type enough, but then I would think that rule would apply to casting with "(T)" as well.

like image 389
Edward Tanguay Avatar asked Jul 24 '09 15:07

Edward Tanguay


People also ask

Should I use as or <> to cast?

The as operator can only be used on reference types, it cannot be overloaded, and it will return null if the operation fails. It will never throw an exception. Casting can be used on any compatible types, it can be overloaded, and it will throw an exception if the operation fails.

What is type casting error?

Above code type casting object of a Derived class into Base class and it will throw ClassCastExcepiton if b is not an object of the Derived class. If Base and Derived class are not related to each other and doesn't part of the same type hierarchy, the cast will throw compile time error.


3 Answers

Because 'T' could be a value-type and 'as T' makes no sense for value-types. You can do this:

public T GetMainContentItem<T>(string moduleKey, string itemKey)
    where T : class
{
    return GetMainContentItem(moduleKey, itemKey) as T;
}
like image 57
n8wrl Avatar answered Nov 11 '22 17:11

n8wrl


If T is a value type this is an exception, you need to make sure T is either Nullable or a class.

like image 36
Yuriy Faktorovich Avatar answered Nov 11 '22 16:11

Yuriy Faktorovich


Is T a value type? If so, if the as operator fails, it will return null, which cannot be stored in a value type.

like image 1
spoulson Avatar answered Nov 11 '22 16:11

spoulson