IDictionary Get Value Or Create - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IDictionary

Description

IDictionary Get Value Or Create

Demo Code


using System.Threading.Tasks;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System;/*w  w w .ja va 2s  . co m*/

public class Main{
        public static T GetValueOrCreate<T>(this IDictionary<string, object> dictionary, string key, Func<T> create)
        {
            object value;
            if (!dictionary.TryGetValue(key, out value))
            {
                value = create();
                if (value != null)
                {
                    // todo should we throw if null?
                    dictionary.Add(key, value);
                }
            }
            return (T)value;
        }
}

Related Tutorials