Note: This article was originally published in 2011. Some steps, commands, or software versions may have changed. Check the current .Net documentation for the latest information.
In this step-by-step guide, you’ll learn initialize a .net dictionary at the variable declaration level. .
Prerequisites
Before you begin, make sure you have:
- Visual Studio or .NET CLI installed
- .NET Framework or .NET Core SDK
- Basic C# programming knowledge
How to: Initialize a Dictionary with a Collection Initializer
Sometimes in your project you want to initialize a Dictionary or other sort of collection at the declaration level so you don’t have to manually use the .add() methods and write a separate method in which to execute them. A prime example is a dictionary that is going to be static and used across the entire application and you don’t expect it to change. The code below offers an example of how to initialize a dictionary when you’re declaring the variable:
Dictionary<int, StudentInfo> students = new Dictionary<int, StudentInfo>()
{
{ 111, new StudentInfo {FirstName="Sachin", LastName="Karnik", PhoneNumber="123-456-7890"}},
{ 112, new StudentInfo {FirstName="Dina", LastName="Salimzianova", PhoneNumber="123-456-7890"}},
{ 113, new StudentInfo {FirstName="Andy", LastName="Ruth", PhoneNumber="123-456-7890"}}
};
StudentInfo
Summary
You’ve successfully learned initialize a .net dictionary at the variable declaration level. If you run into any issues, double-check the prerequisites and ensure your .Net environment is properly configured.
Related Articles
- Entity Framework 4: Any way to know the plural form of an Entity Type?
- Entity Framework - Why can’t I see the child entities of my entity
- Enumeration: What are the different SharePoint permission levels and their enumeration values?
- Error 1 SQL03006: User: [ ] has an unresolved reference to Login [ ]