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.
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.
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.
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;
}
If T is a value type this is an exception, you need to make sure T is either Nullable or a class.
Is T
a value type? If so, if the as
operator fails, it will return null
, which cannot be stored in a value type.
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