Tries to read value and returns the value if successfully read. Otherwise return default value for value's type. - CSharp System.Collections

CSharp examples for System.Collections:IDictionary

Description

Tries to read value and returns the value if successfully read. Otherwise return default value for value's type.

Demo Code


using System.Collections.Generic;

public class Main{
        /// <summary>
        /// Tries to read value and returns the value if successfully read. Otherwise return default value
        /// for value's type.
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="dictionary"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static TValue TryGetAndReturn<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
        {/*w w  w  . j ava 2 s .co  m*/
            TValue retValue;
            if (!dictionary.TryGetValue(key, out retValue))
            {
                retValue = default(TValue);
            }
            return retValue;
        }
}

Related Tutorials