/// <summary>Gets the value associated with the specified key and casts the value to the desired type.</summary>
        /// <returns>true if the <see cref="T:System.Collections.Generic.Dictionary`2" /> contains an element with the specified key; otherwise, false.</returns>
        /// <param name="dictionary">The dictionary to retrieve the value from.</param>
        /// <param name="key">The key of the value to get.</param>
        /// <param name="value">When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref name="value" /> parameter. This parameter is passed uninitialized.</param>
        public static bool TryGetValueCast<T, V, C>(this IDictionary<T, V> dictionary, T name, out C value)
        {
            return TryGetValueCast(dictionary, name, out value, default(C));
        }

        /// <summary>Gets the value associated with the specified key and casts the value to the desired type.</summary>
        /// <returns>true if the <see cref="T:System.Collections.Generic.Dictionary`2" /> contains an element with the specified key; otherwise, false.</returns>
        /// <param name="dictionary">The dictionary to retrieve the value from.</param>
        /// <param name="key">The key of the value to get.</param>
        /// <param name="value">When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref name="value" /> parameter. This parameter is passed uninitialized.</param>
        /// <param name="defaultValue">The default value to return if unable to fetch using key.</param>
        public static bool TryGetValueCast<T, V, C>(this IDictionary<T, V> dictionary, T key, out C value, C defaultValue)
        {
            if (dictionary == null)
            {
                throw new ArgumentNullException("dictionary");
            }

            try
            {
                value = (C)Convert.ChangeType(dictionary[key], typeof(C));
            }
            catch
            {
                value = defaultValue;
                return false;
            }

            return true;
        }

Add comment



biuquote
  • Comment
  • Preview
Loading






Created by: X

Just another personal website in this crazy online world

Name of author Dean Lunz (aka Created by: X)
Computer programming nerd, and tech geek.
About Me -- Resume