Quick actions

cmd+k|ctrl+k

Navigation

Languages

C# defaultdict

Snippet info

Language

Csharp

Visibility

public

Author

hyrious

Created

2020-10-24T11:08:40Z

Updated

2020-10-24T11:08:40Z

using System;
using System.Collections.Generic;

public class DefaultDictionary<TKey, TValue> : Dictionary<TKey, TValue> where TValue : new()
{
    public new TValue this[TKey key]
    {
        get
        {
            TValue val;
            if (!TryGetValue(key, out val))
            {
                val = new TValue();
                Add(key, val);
            }
            return val;
        }
        set { base[key] = value; }
    }
}

class MainClass {
    static void Main() {
        var d = new DefaultDictionary<int, int>();
        d[0]++;
        Console.WriteLine(d[0]);
    }
}
INFO