A useful(I think) little generic dictionary trick.


New to learning C#, actually new to learning any software development or computer science heavy related skills. However, I've lurking this section and find cool tips and advice from time to time.

This time I thought I'd share a little trick I found some where off stack overflow I think, forgot where now but credits to google and people with their ingenious process's. Maybe some one will find a use for it like I had, or perhaps just wanted..

Here it is. It lets you access generic objects from a dictionary and actually use their direct values, if that makes sense.

public class GenericDictionary { private readonly Dictionary<string, object> _dict = new Dictionary<string, object>(); public void Add<T>(string key, T value) where T : class { _dict.Add(key, value); } public T GetValue<T>(string key) where T : class { return _dict[key] as T; } } 

So it could be used(not useful in this context, but you get the idea of what it does):

 public class Example : ExampleBase { public string Name { get; set; } public int Life { get; set; } } private static void Main() { var genericDict = new GenericDictionary(); genericDict.Add("Testing", new Example {Name = "IAmAName",Life = GetCurLife()}); var valueExample = genericDict.GetValue<Example>("Testing"); Console.WriteLine(valueExample.Name + " : " + valueExample.Life); } 

by JacobKemple via /r/csharp

Leave a Reply