Are there any guidelines for when I should use Tuple.Create() instead of new Tuple() ?
There must be a reason for Microsoft having 2 ways to create the same object. Speed differences or other known advantages/disadvantaes?
Are there any guidelines for when I should use Tuple.Create() instead of new Tuple() ?
There must be a reason for Microsoft having 2 ways to create the same object. Speed differences or other known advantages/disadvantaes?
Sadly in C# constructors don't do type inference. So you can't write:
Tuple<int, int> xxx = new Tuple(1, 2);
while methods do it:
Tuple<int, int> xxx = Tuple.Create(1, 2);
for using constructors you need:
Tuple<int, int> xxx = new Tuple<int, int>(1, 2);
This is more verbose.
Note that if type inference doesn't work for you (because you want a tuple of a different type than the parameters you are passing):
Tuple<object, object> xxx = Tuple.Create("A", "B"); // Invalid
then they are equivalent for verbosity:
Tuple<object, object> xxx = Tuple.Create<object, object>("A", "B");
Tuple<object, object> xxx = new Tuple<object, object>("A", "B");
Tuple<object, object> xxx = Tuple.Create((object)"A", (object)"B");
As seen from the source code Tuple.Create(item1)
is just calling new Tuple<T1>(item1)
. So, there is not any speed difference between them.
public static Tuple<T1> Create<T1>(T1 item1) {
return new Tuple<T1>(item1);
}
So, you can create your collection with both ways:
Tuple<int> myTuple = Tuple.Create(1); // This one uses type inference
Tuple<int> myTuple = new Tuple<int>(1);
But, of course there is a reason of the existence of both constructor and generic method. Constructors in C# can't support type inference. So, they have to create some generic method to support type inference. For example, this will give you compiler error:
Tuple<int> myTuple = new Tuple(1); // Oops, compiler error
So, instead of writing the above code, we can write this thanks to Create()
method:
Tuple<int> myTuple = Tuple.Create(1);
By the way, you can read Eric Lippert's answer for more information, if you want to know why can't the C# constructor infer type.
No speed differences but since the Create
is a generic method so the compiler can infer the generic argument types for you.This is not possible for the constructor.