To create an empty dictionary in C#, you can use the `Dictionary
We can create an empty dictionary in C# where the keys are integers and the values are strings. This example demonstrates how to initialize an empty dictionary and add key-value pairs to it.
For example,
using System.Collections.Generic;
.myDictionary
with integer keys and string values.Add
method.using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Declare and initialize an empty dictionary
Dictionary<int, string> myDictionary = new Dictionary<int, string>();
// Add key-value pairs to the dictionary
myDictionary.Add(1, "One");
myDictionary.Add(2, "Two");
myDictionary.Add(3, "Three");
// 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: One Key: 2, Value: Two Key: 3, Value: Three
We can create an empty dictionary in C# where the keys are strings and the values are doubles. This example demonstrates how to initialize an empty dictionary and add key-value pairs to it.
For example,
using System.Collections.Generic;
.myDictionary
with string keys and double values.Add
method.using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Declare and initialize an empty dictionary
Dictionary<string, double> myDictionary = new Dictionary<string, double>();
// Add key-value pairs to the dictionary
myDictionary.Add("A", 1.1);
myDictionary.Add("B", 2.2);
myDictionary.Add("C", 3.3);
// Print the dictionary contents
Console.WriteLine("Dictionary contents:");
foreach (KeyValuePair<string, double> kvp in myDictionary)
{
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
}
}
}
Dictionary contents: Key: A, Value: 1.1 Key: B, Value: 2.2 Key: C, Value: 3.3
In this tutorial, we learned How to create an Empty Dictionary in C# language with well detailed examples.