David Thielen
David Thielen

Reputation: 33046

Can I use the default class for a generic?

I have a class defined as:

public class FindResultEx <TL> where TL : TagLocation
{
}

Three questions on this. First is there a way to create an instance of this class where I go new FindResultEx() and it's the same as new FindResultEx()<TagLocation>?

Second, is there a way to have a returned value declared as being of type FindResultEx and it then assumes it's FindResultEx<TagLocation>?

Third, if I do define or cast something to FindResultEx<TagLocation>, that will handle objects of type FindResultEx<ExtendedFromTagLocation> - correct?

Upvotes: 0

Views: 66

Answers (3)

johnny 5
johnny 5

Reputation: 21033

I just want to point out that your first and second question is kind of possible if you just overload the class with a default.

public class FindResultEx <TL> where TL : TagLocation
{
}

public class FindResultEx: FindResultEx<TagLocation>
{
}

The third question is possible using an interface with Covariance

Upvotes: 0

Grax32
Grax32

Reputation: 4069

FindResultEx and FindResultEx<T> are 2 completely different types.

However, you can create a class FindResultEx that inherits from FindResultEx()<TagLocation>.

This creates an inheritance relationship such that any FindResultEx IS a FindResultEx<TagLocation> but an object of type FindResultEx<TagLocation> IS NOT a FindResultEx.

Upvotes: 1

xneg
xneg

Reputation: 1368

First and second questions - no. FindResultEx and FindResultEx<T> are two completely different classes. Third question - actually no. But you can use interface with covariant parameter like this IFindResultEx<out T>. You may read more about Covariance from here.

Upvotes: 2

Related Questions