-1

Is there a generic way (preferably with an extension method) that you can retrieve values (could be decimal, short, int or string) casted to the right type from a Dictionary<string, object> without it failing when the key does not exist?

John Smith
  • 36
  • 4

1 Answers1

2

you can do the following:

using System;
using System.Collections.Generic;

public static class DictionaryExtensions
{
    public static T GetValue<T>(this Dictionary<string, object> dictionary, string key)
    {
        object value = null;
        if (!dictionary.TryGetValue(key, out value))
        {
            throw new KeyNotFoundException(key);
        }

        return (T)Convert.ChangeType(value, typeof(T));
    }
}

edit: If you don't want it to throw anything, just remove the line that throws a new KeyNotFoundException. I find it handy to have that, because KeyNotFoundException never includes the friggin name of the column not found. This way, the error message will BE the column name :-)

Riegardt Steyn
  • 5,431
  • 2
  • 34
  • 49
  • Why not just use `Convert.ChangeType()`? http://msdn.microsoft.com/en-us/library/dtb69x08(v=vs.110).aspx – Ric Dec 03 '14 at 13:20
  • THis will throw when the key does not exist, also why all the `ConvertTo...` calls. If the value is a T then a cast will suffice. – Ben Robinson Dec 03 '14 at 13:27
  • As the method `Convert.ChangeType()` returns an `object`, can just use it like this: return `(T)Convert.ChangeType(value, typeof(T));` – Ric Dec 03 '14 at 13:28