Generics: How can I create 'optional' Type parameters

  • Thread starter Thread starter john
  • Start date Start date
J

john

Hi to All,

Suppose I would like to implement a generic class with three type
parameters:

class UniversalClass<TA, TB, TC>()
where TA: A, new()
where TB: B, new()
where TC: C, new()

The class has many 'use case' so it can be happen that TA or TB or TC (or TA
and TB or etc..)is meaningless. (similar to null actual parameters) There
are to many combinations

How can I instantiate a closed type instance from this generic in this cases
and how can I detect in UniversalClass's code this cases?

What I've tried:

I've created a NullTypeParamerer class for this purpose, and I test for it
in UniversalClass's constructor:
if( typeof(NullTypeParameter).IsAssignableFrom(typeof(TA)) ) {...}

My problem that in case I must use 'typeless' where clause like this:

class UniversalClass<TA, TB, TC>()
where TA: NullTypeParameter, new()
where TB: NullTypeParameter, new()
where TC: NullTypeParameter, new()

and all of A, B, C actual types must be inherited from NullTypeParameter. I
am not happy with this...

Any ideas?
 
john said:
Suppose I would like to implement a generic class with three type
parameters:

class UniversalClass<TA, TB, TC>()
where TA: A, new()
where TB: B, new()
where TC: C, new()

The class has many 'use case' so it can be happen that TA or TB or TC (or TA
and TB or etc..)is meaningless. (similar to null actual parameters) There
are to many combinations

How can I instantiate a closed type instance from this generic in this cases
and how can I detect in UniversalClass's code this cases?

You can overload the generic type name 'UniversalClass' based on the
number of generic parameters. In other words, use overloading to
simulate default argument values in the same way as one does for normal
methods.

To fill in your default value, you could have each type with fewer
parameters derive from the type with one more parameter, and pass in the
default type as an argument to the ancestor.

If you can't choose a meaningful default type, then you'll need separate
class definitions for each instance, but you can still get the
overloading based on generic parameter count.

-- Barry
 
"john" <[email protected]> a écrit dans le message de (e-mail address removed)...

| Suppose I would like to implement a generic class with three type
| parameters:
|
| class UniversalClass<TA, TB, TC>()
| where TA: A, new()
| where TB: B, new()
| where TC: C, new()
|
| The class has many 'use case' so it can be happen that TA or TB or TC (or
TA
| and TB or etc..)is meaningless. (similar to null actual parameters) There
| are to many combinations

Optional type parameters just do not make sense. Generic classes are fixed,
typesafe classes that are meant to be totally predictable in their
behaviour. Are you sure that you are not trying to achieve some other goal ?

Joanna
 
Back
Top