where T : ISomeInterface //... ...">

Is it possible to use "implicit" type type parameters in C #

I have a generic type:

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

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

+4
source share
2 answers

No, there is no way to express it. If you want to be able to refer to X inside Source , it must be a type parameter.

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

+9
source

If you use a generic type, you tell the compiler that you are going to provide the actual type when creating a particular instance. With your code, if you tried to do

 Source<string> s = new Source<string>(); 

the compiler would know that T is actually a string in the class, but you are not giving the compiler any information about what X will be. However, depending on what you want to do, you can use the has connection with a bare-type interface instead of using inheritance. The following code compiles, for example:

 public interface ISomeInterface<X> { void SomeMethod(X someparam); } public class Source<T> { public void MyMethod<X>(ISomeInterface<X> someConcreteInstance) where X:T { } } 
+1
source

Source: https://habr.com/ru/post/1340606/


All Articles