To set a default value for a key in a dictionary in C#, you can check if the key exists using the `ContainsKey` method. If the key does not exist, you can add the key with a default value.
We can set a default value for a key in a dictionary in C# using the `ContainsKey` method. This example demonstrates how to check if a key exists and set a default value if it does not.
For example,
using System.Collections.Generic;
.myDictionary
with integer keys and string values.using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Declare and initialize a dictionary
Dictionary<int, string> myDictionary = new Dictionary<int, string>();
// Key to check
int keyToCheck = 1;
// Default value to set if key does not exist
string defaultValue = "Default";
// Check if the key exists and set default value if it does not
if (!myDictionary.ContainsKey(keyToCheck))
{
myDictionary[keyToCheck] = defaultValue;
}
// Print the dictionary contents
Console.WriteLine("Dictionary contents:");
foreach (KeyValuePair<int, string> kvp in myDictionary)
{
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
}
}
}
Dictionary contents: Key: 1, Value: Default
We can create a helper method to set a default value for multiple keys in a dictionary in C#. This example demonstrates how to use a helper method to set default values for keys.
For example,
using System.Collections.Generic;
.myDictionary
with integer keys and string values.SetDefaultValue
to set default values for keys.using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Declare and initialize a dictionary
Dictionary<int, string> myDictionary = new Dictionary<int, string>();
// Helper method to set default value
void SetDefaultValue(Dictionary<int, string> dict, int key, string defaultValue)
{
if (!dict.ContainsKey(key))
{
dict[key] = defaultValue;
}
}
// Set default values for multiple keys
SetDefaultValue(myDictionary, 1, "DefaultOne");
SetDefaultValue(myDictionary, 2, "DefaultTwo");
// Print the dictionary contents
Console.WriteLine("Dictionary contents:");
foreach (KeyValuePair<int, string> kvp in myDictionary)
{
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
}
}
}
Dictionary contents: Key: 1, Value: DefaultOne Key: 2, Value: DefaultTwo
In this tutorial, we learned How to Set a Default Value for a Key in a Dictionary in C# language with well detailed examples.