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

CSharp examples for System.Collections.Generic:IDictionary

Description

IDictionary Get Value Or Default

Demo Code

//   Copyright (c) Stephan Burguchev 2012-2013. All rights reserved.
using System.Collections.Generic;

public class Main{
        public static TValue GetValueOrDefault<TValue, TKey>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue = default(TValue))
        {/*from  w  w  w  . jav  a2s . com*/
            TValue value;
            if (dictionary.TryGetValue(key, out value))
            {
                return value;
            }

            return defaultValue;
        }
        public static T GetValueOrDefault<T>(this IDictionary<string, object> dictionary, string key, T defaultValue = default(T))
        {
            object value;
            if (dictionary.TryGetValue(key, out value) && value is T)
            {
                return (T)value;
            }

            return defaultValue;
        }
}

Related Tutorials