Dictionary initialization access to Key value

I have this situation :

public Class Device
{
}
public Class Response
{
   Response(Device device){ ... }
}

public class DeviceManager
{

private Dictionary<Device, Response> behaviours = new Dictionary<Device, Behaviour>{
{
new Device, new Response(...here I want the to send current key value !!!... )}
}
}

Can I access current value of key by current c# semantic means? I know I am very lazy.

Jon Skeet
people
quotationmark

You can't do that in a field initializer. You'd have to put it in a constructor:

public class DeviceManager
{
    private Dictionary<Device, Response> behaviours =
        new Dictionary<Device, Behaviour>();

    public DeviceManager()
    {
        Device device = new Device();
        behaviours.Add(device, new Response(device));
    }
}

With C# 6 you could do it with an extension method on Dictionary<Device, Response>:

public static void Add(
    this Dictionary<Device, Response> dictionary,
    Device device)
{
    dictionary.Add(device, new Response(device));
}

Then:

... = new Dictionary<Device, Response> { new Device() };

... but I don't think I'd do that.

people

See more on this question at Stackoverflow