Jump to content

What is outputted if the value key for TryGetValue doesn't exist? (C#)

RileyTheFox

Hello. I'm making a C# application and was wondering, if I used dictionary.TryGetValue() on a key that doesn't exist, what would the out be?

 

For example, the dictionary has the key type string and a value of int and contains 2 keys, "a" and "b". If I tried to do dictionary.TryGetValue("c", out int value); What would be outputted)

 

Would it be null? Or would it be 0, as Integers can't be null, they are just 0 otherwise.

 

Thanks.

CPU: Intel Core i7 8700  

GPU: Gigabyte GeForce GTX 1070

MOBO: ASUS Z370-F STRIX  

RAM: 16GB Corsair Vengeance DDR4 2133MHz

Link to comment
Share on other sites

Link to post
Share on other sites

It would return false:

Quote

Returns
Boolean
true if the Dictionary<TKey,TValue> contains an element with the specified key; otherwise, false.

https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.trygetvalue?view=netframework-4.7.2

 

The way you're suppose to use this function, as far as I can see, is by checking if what you want to do is a valid thing (e.g. you're not trying to place a string of characters into an int) and do something with the true/false you receive.

 

e.g. in your example, if you tried to input 'c'  into an int, it would return false and you don't try to place that input into the int, while if it returns true, you do place that into the int.

"We're all in this together, might as well be friends" Tom, Toonami.

 

mini eLiXiVy: my open source 65% mechanical PCB, a build log, PCB anatomy and discussing open source licenses: https://linustechtips.com/topic/1366493-elixivy-a-65-mechanical-keyboard-build-log-pcb-anatomy-and-how-i-open-sourced-this-project/

 

mini_cardboard: a 4% keyboard build log and how keyboards workhttps://linustechtips.com/topic/1328547-mini_cardboard-a-4-keyboard-build-log-and-how-keyboards-work/

Link to comment
Share on other sites

Link to post
Share on other sites

18 hours ago, EvilCat70 said:

Hello. I'm making a C# application and was wondering, if I used dictionary.TryGetValue() on a key that doesn't exist, what would the out be?

 

For example, the dictionary has the key type string and a value of int and contains 2 keys, "a" and "b". If I tried to do dictionary.TryGetValue("c", out int value); What would be outputted)

 

Would it be null? Or would it be 0, as Integers can't be null, they are just 0 otherwise.

 

Thanks.

And out parameters require an uninitialized variable for example the Int will be 0 as it is it's value uninitialized. The way you are supposed to use the tryget is using an If statement condition. Here's the correct way to use it

 

// uninitialized int for the dictionary search
int value;

// try get return true if it finds a key and fill the out parameter with what it found
if(dictionary.TryGetValue("c", out int value))
{
    // we found the key, show the user what you found
    // since it returned true the variable value has been it's value set to what the dictionary contained
    // Take important note that if possible this value is by reference. Here since it's a primitive type (int)
    // the return is by value but if it would have been a class you would have had a reference to it.
    MessageBox.Show("the Key [c] contain the value " + value.ToString());
}
else
{
    // key was not found what do you want to do ? perhaps add that key with some basic value or soemthing else
}

 

Your int could have been null if you had declare your dictionary to use nullable ints which are declared like so :

 

// very normal integer
int myStandardInt;

// integer that allow null value. This is also true for "nearly" all types there is including custom objects
int? myNullableInt;

 

Link to comment
Share on other sites

Link to post
Share on other sites

false would be returned, it returns a boolean - same for most types try parsing in C# AFAIK

 

string val = "";
bool success = dictionary.TryGetValue('cookies', out val);
if(sucess) 
	Console.WriteLine("Eat" + val);
else 
	Console.WriteLine("im hungry");

(hopefully a more simple example)

Link to comment
Share on other sites

Link to post
Share on other sites

  • 3 years later...

I'm sorry to necro this thread from 2019. I got here through a Google search. The OP surely got their answer by now, but if anyone else ends up here I want to add my two cents.


TryGetValue assigns the value if it is found in the dictionary, or it assigns the default value for that type if it is not found.
 

string searchKey = "mySearchTerm";
int outputValue = 7; // assigning a value here isn't worthwhile because...

bool success = dictionary.TryGetValue(searchKey, out outputValue);

if (success)
{
    // outputValue now equals dictionary[searchKey].
}
else
{
    // outputValue equals default(int) or 0, not 7.
}

// ...the outputValue will never be 7 when read. The compiler should ignore the assignment of 7, and your IDE should recommend inlining.


Inlining the declaration means you don't have to declare it sooner.

string searchKey = "mySearchTerm";

if (dictionary.TryGetValue(searchKey, out string outputValue))
{
    // outputValue equals dictionary[searchKey].
}

// Note that outputValue is still in scope here.
outputValue = 9;

 

However...

string searchKey = "mySearchTerm";
int outputValue;

dictionary.TryGetValue(searchKey, out int outputValue); // compiler error. outputValue is already defined in this scope.

 

So, if only keys "a" and "b" have values but the key given is "c", then the out value would be 0 because that is the default for an int.


If you want to try some of this out, I like doing quick experiments in .NET Fiddle

I hope this constructively adds to the conversation and maybe saves another Googler some time some day. 🙂

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×