Why can't the type conversion of `this` be implicitly inferred from the generic contraint?

I have the following class:

public class Item<TItem>
    where TItem : Item<TItem>
{
    void GetReference()
    {
        TItem item = this;
    }
}

Here TItem item = this; generates a compiler error "can't convert Item<TItem> implicitly to TItem".

But why do we need a conversion here? We have defined the constraint where TItem : Item<TItem>, so one can think that no conversion is needed at all since the two types are the same, aren't they?

Btw an explicit conversion is available. This also is stated in the compiler error.

Jon Skeet
people
quotationmark

Because it wouldn't be safe. Consider:

public class GoodItem : Item<GoodItem>
{
    // No problem
}

public class EvilItem : Item<GoodItem>
{
    // GetReference body would be equivalent to 
    // GoodItem item = this;
    // ... but this *isn't* a GoodItem, it's an EvilItem!
}

EvilItem satisfies the constraint for TItem with no problems - GoodItem is indeed derived from Item<GoodItem>.

There's no way of expressing a relationship between the class being declared and a type parameter, which is what you really want.

people

See more on this question at Stackoverflow