Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use "implicit" generic type parameters in c#

Tags:

c#

.net

generics

I have a generic type:

public class Source<T> where T : ISomeInterface<X> //...

Now, my problem is, I really don't want to modify Source<T> to Source<T,X>, but I want to use X inside Source.
Is it possible in any way?

like image 900
TDaver Avatar asked Feb 21 '11 11:02

TDaver


People also ask

Which types can be used as arguments of a generic type?

The actual type arguments of a generic type are. reference types, wildcards, or. parameterized types (i.e. instantiations of other generic types).

Can dynamic type be used for generic?

Not really. You need to use reflection, basically. Generics are really aimed at static typing rather than types only known at execution time.

Can generic classes be constrained?

You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter.

Can type parameters be inherited?

You can't inherit from the generic type parameter.


1 Answers

No, there's no way of expressing that. If you want to be able to refer to X within Source, it has to be a type parameter.

Bear in mind that T could implement (say) ISomeInterface<string> and ISomeInterface<int>. What would X be in that case?

like image 177
Jon Skeet Avatar answered Oct 01 '22 03:10

Jon Skeet