C # cannot distinguish T from T

I have a common set of MyCollection<T> that I created, and everything works fine, except for this new Apply function that I add:

 class MyCollection<T> { T value; public MyCollection(T starter) { value = starter; } public MyCollection<S> Apply<T, S>(Func<T, S> function) { return new MyCollection<S>(function(value)); // error in function(value) } } 

This gives me an error that I have never seen before:

 Argument 1: cannot convert from 'T' to 'T [C:\folder\code.cs (line number)]' 

What are the two types of T ? What happened to the conversion I'm trying to do?

+4
source share
3 answers

The problem is that a parameter of type T in

 class MyCollection<T> 

- not the same type parameter as in

 Apply<T, S> 

so your function takes a different type than value

if you change

 Apply<T, S> 

to

 Apply<S> 

your code will compile

+7
source

One T comes from MyCollection<T> and one from Apply<T, S> . Apply<S> should be enough.

+5
source

He is trying to use a generic class type for a generic method type. Remove T from the signature of the Apply method.

 class MyCollection<T> { T value; public MyCollection(T starter) { value = starter; } public MyCollection<S> Apply<S>(Func<T, S> function) { return new MyCollection<S>(function(value)); } } 
+1
source

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


All Articles