Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is Tuple<T1,T2>.Create<T1,T2>(T1 item1, T2 item2) implemented?

I'm trying to implement a similar method as Tuple<T1,T2>.Create<T1,T2>(T1 item1, T2 item2), but I still have to specify the type parameters whereas Tuple.Create infers them.

I think the definition is right. What am I doing wrong? Here's my code:

public class KeyValuePair<K, V>
{
    public K Key { get; set; }       

    public V Value { get; set; }

    public static KeyValuePair<K, V> Create<K, V>(K key, V value)
    {
        return new KeyValuePair<K, V> { Key = key, Value = value };
    }
}
like image 513
Ronnie Overby Avatar asked Aug 18 '11 20:08

Ronnie Overby


People also ask

How do you create a tuple?

Creating a Tuple A tuple in Python can be created by enclosing all the comma-separated elements inside the parenthesis (). Elements of the tuple are immutable and ordered. It allows duplicate values and can have any number of elements.

How do you instantiate a new tuple?

You can instantiate a Tuple<T1, T2> object by calling either the Tuple<T1, T2>(T1, T2) constructor or by the static Tuple. Create method. You can retrieve the value of the tuple's elements by using the read-only Item1 and Item2 instance property.

Can tuple have 3 elements?

A tuple is a data structure that has a specific number and sequence of values. The Tuple<T1,T2,T3> class represents a 3-tuple, or triple, which is a tuple that has three components.

What is tuple in C# with example?

A tuple is a data structure that contains a sequence of elements of different data types. It can be used where you want to have a data structure to hold an object with properties, but you don't want to create a separate type for it. Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>


2 Answers

You'll want to create a non-generic version of the class.

public class KeyValuePair
{
    public static KeyValuePair<K, V> Create<K, V>(K key, V value)
    {
        return new KeyValuePair<K, V>(key, value);
    }
}
like image 158
ChaosPandion Avatar answered Sep 22 '22 05:09

ChaosPandion


I figured it out. It's not defined as a static method on the Tuple<T1,T2> class, but on the Tuple class.

like image 44
Ronnie Overby Avatar answered Sep 21 '22 05:09

Ronnie Overby