mcmorry mcmorry - 1 month ago 17
C# Question

cannot convert Key<T> expression to type Key<T>?

I can't find what's wrong in this code and the error didn't help me much:

public class Track<T> {

readonly List<Key<T>> _keys = new List<Key<T>>();

public void AddKey<T>(float time, T value) {
var key = new Key<T> {
Time = time,
Value = value
};
_keys.Add(key); // <== Error: cannot convert Key<T> expression to type Key<T>
}
}

public struct Key<T> {
public float Time;
public T Value;
}

Answer

You've redefined template in the method:

// Here's one "T"
public class Track<T> {
    readonly List<Key<T>> _keys = new List<Key<T>>();

    // ... And here is a different "T" which hides original (from Track<T>) one 
    // the declaration equals to 
    // public void AddKey<K>(float time, K value) {
    public void AddKey<T>(float time, T value) {
      // T has been redefined, so "new Key<T>" (with redefined T)
      // is not equal to Key<T> from List<Key<T>> _keys which uses class template T
      ... 
    }
}

try removing T from the method:

public class Track<T> {
    ...    
    // No "<T>" declaration here, uses "T" from Track<T>
    public void AddKey(float time, T value) {
        ...
    }
}