ExtensionMethod.NET Home of 820 C#, Visual Basic, F# and Javascript extension methods

ValidateAndConvertDictionaryData

Dictionary Extension

Source

public static class DictionaryExtensions
{
    public static T ValidateAndConvertDictionaryData<T>(this Dictionary<string, object> dictionary, string dictionaryKey)
    {
        if (dictionary != null && dictionary.ContainsKey(dictionaryKey))
        {
            object dictionaryValue;
            dictionary.TryGetValue(dictionaryKey, out dictionaryValue);

            if (dictionaryValue != null)
            {
                return dictionaryValue.TryToCast<T>();
            }
        }

        return default(T);
    }

   public static T TryToCast<T>(this object value)
    {
        if (value is T)
        {
            return (T)value;
        }
        try
        {

            if (typeof(T).IsEnum)
            {
                return (T)Enum.Parse(typeof(T), value.ToString());
            }

            return (T)Convert.ChangeType(value, typeof(T));
        }
        catch (Exception)
        {
            return default(T);
        }

    }

}

Example

Dictionary<string, object> dictionary = new Dictionary<string, object> {{"FOO", 1}};
  string foo = dictionary.ValidateAndConvertDictionaryData<string>("FOO");

Author: Cem Basaranoglu

Submitted on: 22 dec 2016

Language: C#

Type: Dictionary Extensions

Views: 1648