When getting a key from a Dictionary you're not sure exists, you would usually use TryGetValue
instead of ContainsKey
+ the get indexer to avoid the overhead of checking the key twice. In other words, this:
string password;
if (accounts.TryGetValue(username, out password))
{
// use the password
}
would be preferred to this:
if (accounts.ContainsKey(username))
{
string password = accounts[username];
}
What if I wanted to check if a key already existed before setting it to a value? For example, I would want to check if a username existed before overwriting it with a new password:
if (!accounts.ContainsKey(username))
{
accounts.Add(username, password);
}
else
{
Console.WriteLine("Username is taken!");
}
vs
// this doesn't exist
if (!accounts.TrySetValue(username, password))
{
Console.WriteLine("Username is taken!");
}
Is there a more performant alternative to ContainsKey
and Add
that does this?