Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# cannot cast T to T

I have a generic collection MyCollection<T> that I've made, and everything works fine except this new function Apply that I'm adding:

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 I've never seen before:

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

What are the two T types? What's wrong with the conversion I'm attempting?

like image 207
Joe Avatar asked Dec 13 '22 05:12

Joe


1 Answers

You problem is that the type parameter T in

class MyCollection<T>

is not the same type parameter as T in

Apply<T, S>

so your function takes another type than the type of value

if you change

Apply<T, S>

to

Apply<S>

your code will compile

like image 73
Terkel Avatar answered Dec 31 '22 16:12

Terkel