Can you declare item names in a ValueTuple value in a Dictionary?

Viewed 527

Is it possible to declare a ValueTuple as a value in a Dictionary, and include names for the items in the ValueTuple?

I've tried:

var x = new Dictionary<String, ValueTuple<name: String, id: String> = {...}

but I didn't really expect that to work, but then neither did this:

var x = new Dictionary<String, ValueTuple<String, String>> = {
  { "mary", (name: "foo", id: "green") }}

note that the previous declaration works without mentioning name and id, but then I can't then access the tuple members by name..

var x = new Dictionary<String, ValueTuple<String, String>> = {
  { "mary", ("foo", "green") }}

var y = x["mary"].foo   // won't work
2 Answers

You can use named tuples in the following way:

var dict = new Dictionary<string, (string name, string id)>();
dict.Add("Mary", ("Foo", "green"));
...
var id = dict["Mary"].id; //get an Id value

This syntax is available starting from C# 7.

If you prefer a collection initializer, you can declare a dictionary like

var dict = new Dictionary<string, (string name, string id)>
{
    { "Mary", ("Foo", "green") }
};

This declaration var y = x["mary"].foo won't work, because foo is value of tuple item, not the name. To get a foo value you should use dict["Mary"].name

Yes and no.

The names are only in the code, not in the data.

You can do this:

var dict = new Dictionary<string, (string, string)>();
dict.Add("Mary", (name: "Foo", id: "green"));
(string foo, string bar) t1 = dict["Mary"];
var v1 = t1.foo; // Foo
var v2 = t1.bar; // green

While the tuple is added to the dictionary with name and id value names, it is retrieved with foo and bar value names.

Related