Erica June
Erica June

Reputation: 31

Assign more specific generic type to less specific type

I'd like to instantiate instances of a generic type and pass them around as if they were generic objects of an interface that they implement, such as below. Clearly, this is not allowed. Why is this, and what is the general practice for handling such situations? thanks.

public class MyType<T> where T : IComparable { }
MyType<IComparable> things = new MyType<Int32>();

this gets error: Cannot implicitly convert type MyType<Int32> to MyType<IComparable>

I want to do this because I need different types of things that I want to pass around to more generic methods such as

public void DoSomething(MyType<IComparable> things) {...}

Upvotes: 2

Views: 116

Answers (1)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112324

The assignment compatibility of generic type arguments does not make the generic type itself assignment compatible. This is why: Let's assume that we declared the generic class like this:

public class MyType<T> where T : IComparable
{
    public T Value { get; set; }
}

And let's assume that this would compile ...

var intObject = new MyType<int> { Value = 42 };
MyType<IComparable> things = intObject; // Does not compile!

... then we could write

// things.Value has the static type IComparable
things.Value = "hello"; // Allowed because string is IComparable

But this is not possible since the underlying object is a MyType<int> and thus its Value property has the type int. Therefore, we are not allowed to substitute a MyType<int> for a MyType<IComparable>.

Upvotes: 2

Related Questions