Is it possible to use named Tuple with generic type declaration?
Asked Answered
B

2

12

I know we can declared a named tuples like:

var name = (first:"Sponge", last:"Bob");

However, I cannot figure out how to combined the named tuple with a generic type, such as Dictionary.

I have tried the below variations, but no luck:

Dictionary<string, (string, string)> name = new Dictionary<string, (string, string)>();

// this assignment yields this message:
// The tuple element name 'value' is ignored because a different name or no name is specified by the 
// target type '(string, string)'.
// The tuple element name 'limitType' is ignored because a different name or no name is specified 
// by the target type '(string, string)'.
name["cast"] = (value:"Sponge", limitType:"Bob");  

// I tried putting the name in front and at the end of the type, but no luck
// Both statements below produce syntactic error:
Dictionary<string, (value:string, string)> name;
Dictionary<string, (string:value, string)> name;

Does anyone know if C# supports the scenario above?

Bybee answered 7/3, 2020 at 21:21 Comment(0)
A
15

You have a two options here. First one is to declare the named tuple with custom item names at Dictionary declaration, like that

var name = new Dictionary<string, (string value, string limitType)>();
name["cast"] = ("Sponge", "Bob"); //or name["cast"] = (value: "Sponge", limitType: "Bob");

And access an items in the following way

var value = name["cast"].value;

Second one is to use an unnamed tuple with default item names (Item1, Item2, etc.)

var name = new Dictionary<string, (string, string)>();
name["cast"] = ("Sponge", "Bob");

Language support for tuples was added in C# 7, please ensure that you are using this language version, or install System.ValueTuple package, if something is missing

Adenoma answered 7/3, 2020 at 21:24 Comment(1)
Thank Pavel...the only I didn't try was putting the name after the type...string value...give mes what I needed...Thank you so much!Bybee
H
3

In this case what matters is the names in the declaration of the Dictionary:

Dictionary<string, (string First, string Last)> SomeDictionary
    = new Dictionary<string, (string, string)>();

Then you can use the names like this:

var value = SomeDictionary["SomeKey"];
var first = value.First;
var last = value.Last;
//var (first, last) = SomeDictionary["SomeKey"]; // alternative, Tuple deconstruction
Historicism answered 7/3, 2020 at 21:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.