Jake
Jake

Reputation: 7773

C# 7.0 Tuple Deduction

When I write this line:

Tuple<string,string> key = (controller, action);

I get this error:

Severity Code Description Project File Line Suppression State Error CS0029 Cannot implicitly convert type '(string controller, string action)' to 'System.Tuple' Project.Web PageMetadata.cs 27 Active

This seems like a fairly straight-forward, intuitive application of the new tuple enhancements that are at the heart of the C#7 updates, and yet it doesn't work. What am I doing wrong?

Upvotes: 9

Views: 2449

Answers (4)

David Arno
David Arno

Reputation: 43254

First of all, you get that error as you are trying to cast the new style tuple (ValueTuple) to the old style tuple (Tuple).

This can be achieved using the ToTuple() extension method:

Tuple<string,string> key = (controller, action).ToTuple();        

But that probably isn't what you are trying to do. If you want to create an instance of a new tuple, you could do:

ValueTuple<string,string> key = (controller, action);

But if you do that, you still end up with the two elements being called Item1 and Item2, which defeats one of the key features of the new tuple syntax: named elements. Change it to use var, and you then get named elements:

var key = (controller, action);
Console.WriteLine(key.controller); // key.controller is now valid

If you really don't like using var (some folk do not), then you can express it longhand to still get those named elements:

(string controller, string action) key = (controller, action); 
Console.WriteLine(key.controller);

Upvotes: 2

Julien Couvreur
Julien Couvreur

Reputation: 4973

If you really need to convert from System.Tuple to System.ValueTuple (used by tuple syntax), or back, there are extension methods: ToTuple and ToValueTuple defined for small arities.

Upvotes: 0

Ousmane D.
Ousmane D.

Reputation: 56433

The new tuples features require the ValueTuple type i.e.

ValueTuple<string, string> key = (controller, action);

or

var key = (controller, action);

it's important to note that a Tuple is a class and ValueTuple is a struct. you should not mix them up. see here for more details about the new tuple features in C# 7.

Upvotes: 12

Joe Sewell
Joe Sewell

Reputation: 6610

Use ValueTuple<string, string> instead of Tuple<string, string>. Tuple<T1,T2> is a system type from before C# 7.0; ValueTuple<T1,T2> is the one that supports the new language features. For more details, see the C# Tuple type guide.

Upvotes: 0

Related Questions