Gets an item from the dictionary, if it's found. Otherwise, returns the specified default value. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IDictionary

Description

Gets an item from the dictionary, if it's found. Otherwise, returns the specified default value.

Demo Code


using System.Collections.Generic;

public class Main{
        /// <summary>
        /// Gets an item from the dictionary, if it's found. Otherwise, 
        /// returns the specified default value.
        /// </summary>
        public static TValue TryGetValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue)
        {/*from ww  w  .  java  2 s.  co m*/
            var result = defaultValue;
            if (!dictionary.TryGetValue(key, out result))
                return defaultValue;

            return result;
        }
        /// <summary>
        /// Gets an item from the dictionary, if it's found.
        /// </summary>
        public static TValue TryGetValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
        {
            return dictionary.TryGetValue(key, default(TValue));
        }
}

Related Tutorials