What if T is invalid in Generics? How to omit angle brackets

I have a class of this type:

class A<TResult> { public TResult foo(); } 

But sometimes I need to use this class as not a general class, i.e. type TResult - void .
I cannot create an instance of the class as follows:

 var a = new A<void>(); 

Also, I would prefer not to specify a type that omits angle brackets:

 var a = new A(); 

I do not want to rewrite the whole class because it does the same.

+7
source share
4 answers

void not a real type in C #, even in FCL there is a corresponding System.Void structure. I'm afraid you need a non-generic version here:

 class A { //non generic implementation } class A<T> : A { //generic implementation } 

you can see in FCL System.Action / System.Action<T> instead of System.Action<void> , and also Task instead of Task<void> .

EDIT From CLI Specification (ECMA-335) :

The following type types cannot be used as arguments to instances (generic types or methods):

Byref types (e.g. System.Generic.Collection.List`1 <string &> - invalid)

Value types that contain fields that can point to the CIL evaluation stack (e.g. List <System.RuntimeArgumentHandle>)

void (e.g. List <System.Void> is invalid)

+8
source

As I wrote in a comment, you can do this well by inheriting from a generic class:

 class A:A<object> { } 

This clearly hides the general parameter, but keep in mind that in my experience this is the wrong way to inherit classes, and every time I did this, I regretted it while my class became more complex.

+4
source

void is simply not a type in C #, so you cannot use it as a type parameter. But, nevertheless, there are times when you want functionality, as if it were one.

In this case, you can use a simple replacement type, most likely a very small structure like System.Reactive.Unit is used in Reactive Extensions.

+1
source

Another option (which seems to be getting the balance) is to use the NullObject design pattern. http://sourcemaking.com/design_patterns/null_object

0
source

All Articles