One-liner to create a dictionary with one entry
I have a method which takes a Dictionary<int, int>
as a parameter
public void CoolStuff(Dictionary<int, int> job)
I want to call that method with one dictionary entry, such as
int a = 5;
int b = 6;
var param = new Dictionary<int, int>();
param.Add(a, b);
CoolStuff(param);
How can I do it in one line?
This is it, if you do not need the a
and b
variables:
var param = new Dictionary<int, int> { { 5, 6 } };
or even
CoolStuff(new Dictionary<int, int> { { 5, 6 } });
Please, read How to: Initialize a Dictionary with a Collection Initializer (C# Programming Guide)
var param = new Dictionary<int, int>() { { 5, 6 } };