Reputation: 193302
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.
Upvotes: 9
Views: 273
Reputation: 48265
Because as T
retrieves null
in case that it cannot cast to T
as opposed to (T)
that throws an exception. So if T
is not Nullable
or class
it can't be null
... i think.
Upvotes: 0
Reputation: 26330
Extending on Yuriy Faktorovichs answer:
public T GetMainContentItem<T>(string moduleKey, string itemKey) where T: class
{
return GetMainContentItem(moduleKey, itemKey) as T;
}
This will do the trick...
Upvotes: 0
Reputation: 21591
Is T
a value type? If so, if the as
operator fails, it will return null
, which cannot be stored in a value type.
Upvotes: 1
Reputation: 19765
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;
}
Upvotes: 23
Reputation: 68667
If T is a value type this is an exception, you need to make sure T is either Nullable or a class.
Upvotes: 6