Consider the following expressions:
new Tuple<int,int>(1,2); Tuple.Create(1,2);
Is there any difference between these two methods of Tuple creation? From my reading it seems to be more a convenient shorthand than anything like object creation in C++ (heap vs stack).
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.
Why should we use Tuples? You may want to use a tuple to represent a set of heterogeneous data and provide an easy way to access that data. You can also take advantage of a tuple to return multiple values from a method or even pass multiple values to a method.
Personally, I find Tuple.Create()
less verbose and easier to read.
There's no difference, under the hood. The Tuple.Create()
overloaded methods are just a bunch of static methods that call the first version you posted:
public static class Tuple { public static Tuple<T1> Create<T1>(T1 item1) { return new Tuple<T1>(item1); } public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return new Tuple<T1, T2>(item1, item2); } public static Tuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) { return new Tuple<T1, T2, T3>(item1, item2, item3); } ...
I suppose one benefit is that, since you don't have to specify the type with Tuple.Create
, you can store anonymous types for which you otherwise wouldn't be able to say what the type is.
public class Person { public string Name { get; set; } public int Height { get; set; } public DateTime BirthDate { get; set; } } var people = new List<Person> { new Person { Name = "Bob", Height = 72, BirthDate = new DateTime(1984,1,1) }, new Person { Name = "Mary", Height = 64, BirthDate = new DateTime(1980,2,2) } }; var oneAnonList = people.Select(x => new { x.Name, x.BirthDate }); var twoAnonList = people.Select(x => new { x.Height, x.Name }); var myTuple = Tuple.Create(oneAnonList, twoAnonList);
This creates a Tuple with two anonymous types, the first is a new { string Name, DateTime BirthDate }
and the second is a new { int Height, string Name }
.
There's still not too terribly much you can do with that, since to pass it to another method, you'd still need to be able to define the "type" of the parameter. So it really comes down to convenience.
The benefit of Tuple.Create
is that you can usually omit the type arguments, eg. Tuple.Create(1,2)
is briefer than new Tuple<int,int>(1,2)
.
If you try omitting the type arguments from the constructor new Tuple(1,2)
you will see error CS0712 "Cannot create an instance of the static class 'Tuple""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With