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?
Asked
Active
Viewed 134 times
-1

John Smith
- 36
- 4
-
1Yes, there is...you just need to write it. – Adriano Repetti Dec 03 '14 at 13:17
-
1Thank you for your insightful contribution – John Smith Dec 03 '14 at 13:35
-
1Maybe I've been pretty ironic but meaning was: first try by yourself, you should first try to solve the problem and then ask on SO when you fail. In this question I just see a requirement, not an attempt. – Adriano Repetti Dec 03 '14 at 13:38
1 Answers
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