Erik Z
Erik Z

Reputation: 4770

How to implement both generic and non-generic version of a class?

I want to implement a non-generic version of my generic class. Like this.

public class ServerSentEvent : ServerSentEvent<NoAdditionalClientInformation>

public class ServerSentEvent<ClientInfo> : IServerSentEvent

To solve this I had to make a dummy/empty class - NoAdditionalClientInformation.

Is there another way to do this without the empty class?

Upvotes: 14

Views: 5844

Answers (1)

poke
poke

Reputation: 387707

Usually you’d just do it the other way around:

public class ServerSentEvent : IServerSentEvent
{}

public class ServerSentEvent<ClientInfo> : ServerSentEvent
{}

That way the generic version is a more specified subtype of the non-generic one allowing you to put more information in it but to use the generic type whereever a non-generic type is expected.

If you do it like you suggested, you would need to have to specify some default type; if you can’t think of a default one, it is probably the wrong order, but in general it might depend on the case.

Upvotes: 18

Related Questions