Edward Tanguay
Edward Tanguay

Reputation: 193302

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.

Upvotes: 9

Views: 273

Answers (5)

bruno conde
bruno conde

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

EricSchaefer
EricSchaefer

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

spoulson
spoulson

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

n8wrl
n8wrl

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

Yuriy Faktorovich
Yuriy Faktorovich

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

Related Questions