The specific exception I’m getting is:
Unable to cast object of type
NbtByteto typeINbtTag<System.Object>
On this line:
tag = (INbtTag<object>)new NbtByte(stream);
Where tag is declared as:
INbtTag<object> tag;
And NbtByte is defined as:
public class NbtByte : INbtTag<byte>
Where IBtTag is:
public interface INbtTag<out T>
I thought by declaring it as out T I would be able to do things like this.
Basically, I want to have a dictionary of IbtTag<T>s,
var dict = new Dictionary<string, INbtTag<object>>();
but where T is of different types (thus I declared it with object). Is this possible?
Interface variance applies only to reference types. Value types (such as ints, bytes, etc., as well as custom structs) are excluded. For example, you cannot use an array of integers as
IEnumerable<object>even though the array isIEnumerable<int>.To solve your issue with the dictionary, you can perhaps elect to define a non-generic interface. (Where your generic interface might expose members as type T, the non-generic interface would simply expose
object.)Say you have
Then you could use your dictionary as
Dictionary<string, INbtTag>.The drawback is that when you implement the interface, you have to implement both. This usually means implementing the generic version implicitly, and the non-generic explicitly. For example: