16

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?

8
  • 2
    do you know the type when you say non generic of generic? if yes then just use it.. Commented Jan 16, 2013 at 7:17
  • 4
    If you look at .NET BCL classes you will notice that the generic versions are child classes of the non generic versions and not the other way round. For example IEnumerable<T> implements IEnumerable. Commented Jan 16, 2013 at 7:18
  • What if the generic class inherited from the non-generic one: public class ServerSentEvent<TClientInfo> : ServerSentEvent and public class ServerSentEvent : IServerSentEvent? Commented Jan 16, 2013 at 7:19
  • 2
    @DarinDimitrov can you give an example of generic class that a child of non-generic? Commented Jan 16, 2013 at 7:21
  • 1
    @lazyberezovsky ChannelFactory<TChannel> inherits from ChannelFactory Commented Jan 16, 2013 at 7:23

1 Answer 1

19

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Could you provide a more detailed example?
@Saibot For what exactly? Maybe you should ask your own question?
Yeah, then it would be marked as duplicate in 10 seconds :D
I would like to see a case where we can benefit implementing both generic and non generic versions. I am having trouble to understand why this is necessary (or is it necessary at all?) and how to use this pattern properly.
@Saibot As an example, see IEnumerable<T> and IEnumerable. IEnumerable<T> inherits from IEnumerable, so every generic enumerable is also a non-generic enumerable. The benefit of this is that anything that works with any enumerable will also work for generic enumerables. Another example would be Task<T> and Task.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.