Jimmy
Jimmy

Reputation: 3264

C# Generics not working as expected

We have a problem with the usage of generics. We have a generic collection of generic keyvalue pair which is defined as follows

public class KeyValueTemplate<K, V> : IGetIdentifier<K>
{
//...
}

public class KeyValueListTemplate<K, V> : ObservableCollection<KeyValueTemplate<K, V>>
{
//....
}

public class KeyValueStringListTemplate : KeyValueListTemplate<string,string> { }

We are using this in the code as follows

public class test
{

   public KeyValueStringListTemplate SetValuesList{get;set;}
   public ObservableCollection<IGetIdentifier<string>> GetList()
   {
     return SetValuesList;
   }

}

The complier is not accepting this. The error is

Cannot convert type 'KeyValueStringListTemplate' to 'System.Collections.ObjectModel.ObservableCollection<IGetIdentifier<string>>

Why?? Both the types are same to me.

Upvotes: 2

Views: 142

Answers (2)

YavgenyP
YavgenyP

Reputation: 2123

Its a matter of covariance in generics, which was not exposed to c#/vb.net before .net 4.
While it seem trivial that you can do this:

IEnumerable<string> strings = new List<string>();
// An object that is instantiated with a more derived type argument 
// is assigned to an object instantiated with a less derived type argument. 
// Assignment compatibility is preserved. 
IEnumerable<object> objects = strings;

which is what your code is doing at the bottom line, it wasnt supported up to .net 4
The article i linked to explanis how to implement it and how it works.

Upvotes: 1

Ilmo Euro
Ilmo Euro

Reputation: 5115

This line

public class KeyValueListTemplate<K, V> : ObservableCollection<KeyValueTemplate<K, V>>

defines a new type, KeyValueListTemplate, that is a subtype of ObservableCollection, so they are different types. KeyValueListTemplatecan be safely converted to ObservableCollection, because it has a superset of ObservableCollection's functionality (by Liskov Substitution Principle), but the opposite conversion is not safe.

Upvotes: 2

Related Questions