Home > Mobile >  How to instantiate a linkedlistNode of a generic type in c#
How to instantiate a linkedlistNode of a generic type in c#

Time:01-06

For example I have a generic class KeyAndValue

public class KeyAndValue<T, U>
{
    public T? key { get; set; }
    public U? value { get; set; }
}

Now I want to instantiate a LinkedListNode<KeyAndValue<int, int>> object

var newNode = new LinkedListNode<KeyAndValue<int, int>>();

I received warning like this

There is no argument given that corresponds to the required formal parameter 'value' of 'LinkedListNode<KeyAndValue<int, int>>.LinkedListNode(KeyAndValue<int, int>)' [146]",

My question is how to create an object that is generic type of generic type?

CodePudding user response:

You can use the existing class KeyValuePair instead of KeyAndValue. Additional you can create a constructor:

public class KeyAndValue<T, U>
    {
        public KeyAndValue(T key, U value)
        {
            this.key = key;
            this.value = value;
        }
        public T? key { get; set; }
        public U? value { get; set; }
    }

Both is possible:

var keyValuePair = new KeyValuePair<int, int>(0, 5);
var linkedListNode1 = new LinkedListNode<KeyValuePair<int, int>>(keyValuePair);

var keyAndValue = new KeyAndValue<int, int>(0, 5);
var linkedListNode2 = new LinkedListNode<KeyAndValue<int, int>>(keyAndValue);
  •  Tags:  
  • Related