Adam Adam - 7 months ago 34
C# Question

Returning a dictionary value in C# without assigning it to a variable?

I want to use the value of a dictionary without assigning it to a variable:

Dictionary<int, string> LayoutByID = new Dictionary<int, string>() {
{ 0, "foo"},
{ 1, "bar"}
// ...

I can for e.g. print the values if I create a variable:

string b;
LayoutByID.TryGetValue(1,out b);
print("Trying Dictionary to retrieve value for 1: " + b);

But I was wondering if there is a simpler way, something like:

print("Trying Dictionary to retrieve value for 1: " + LayoutByID.TryGetValue(1 [???]));

I understand I could write a function with a switch in it that would work similarly, but using Dictionaries might be cheaper as I have a longer list.
Thanks for advice!


You can access the Dictionary with the key like var x = LayoutByID[0]; But you will get an exception, if the Dictionarydoes not contain an entry with that key.

In order to avoid an exception being throw, you can first check if the key exists using LayoutByID.ContainsKey() - and then write your logic for those cases:

if (LayoutByID.ContainsKey(0)) // Check if the key exists (replace 0 with whatever)
    var x = LayoutByID[0]; // Access the value and do whatever with it
    // ...
    // Key doesn't exist:
    // Do something else

or with C# 6.0 you could also print like this

var key = -1;
var myString = string.Empty;
LayoutByID.TryGetValue(key, out myString);
Console.WriteLine($"Trying Dictionary to retrieve value for {key}: {myString ?? "Error: Invalid ID"}");