Search code examples
c#.netgenericscastinggeneric-programming

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.


Solution

  • 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;
    }