Jason
Jason

Reputation: 860

Creation of generic type relying on another type C#

I have a class which is defined as

public class SerializableList<TList, TValue> : IXmlSerializable where TList : IList<TValue>

The issue comes when trying to implement the constructor to make sure I have a TList object.

public SerializableList()
{
    FList = new TList();
}

Which throws the expected error of not having a new() constraint. As I want to be able to use the definition of

var myList = new SerializableList<SortedList<string>, string>();

does this mean I have looking at things the wrong way, or is there a way I can define the new FList object?

Upvotes: 0

Views: 79

Answers (2)

Binary Worrier
Binary Worrier

Reputation: 51711

What you want are Generic Type Constraints

In your instance the class declaration needs to be

public class SerializableList<TList, TValue> 
    : IXmlSerializable where TList : IList<TValue>, new()

Where new() enforces that TList must have a parameterless constructor

Upvotes: 1

Sergei Rogovtcev
Sergei Rogovtcev

Reputation: 5832

public class SerializableList<TList, TValue> : IXmlSerializable
    where TList : IList<TValue>, new()

Upvotes: 2

Related Questions