I'm doing some dynamic A.I. programming and to avoid having to create so many different classes for each use case, so that the parameters can be passed correctly, I thought I'd use an an object bag/container, akin to a dictionary.
In order to support it fully generic, I made the key a Type parameter so I can use it in other projects, which works fine. My issue is, I want to support objects and structs so when it comes to implementing a TryGet
style function, I don't know how to assign the out parameter.
Here is my class:
using System;
using System.Collections.Generic;
namespace mGuv.Collections
{
public class ObjectBag<TKey>
{
private Dictionary<Type, Dictionary<TKey, object>> _objects = new Dictionary<Type, Dictionary<TKey, object>>();
public ObjectBag()
{
}
private bool HasTypeContainer<T>()
{
return _objects.ContainsKey(typeof(T));
}
public bool HasKey<T>(TKey key)
{
if (HasTypeContainer<T>())
{
return _objects[typeof(T)].ContainsKey(key);
}
return false;
}
public void Add<TIn>(TKey key, TIn value)
{
if(!HasTypeContainer<TIn>())
{
_objects.Add(typeof(TIn), new Dictionary<TKey, object>());
}
_objects[typeof(TIn)].Add(key, value);
}
public bool TryGet<TOut>(TKey key, out TOut value)
{
if (HasKey<TOut>(key))
{
value = (TOut)_objects[typeof(TOut)][key];
return true;
}
// As expected, I can't assign value to null
value = null;
// I also can't just return false as value hasn't been assigned
return false;
}
}
}
Is there anyway to assign value to the default of anything that is passed in?
I.e. I want to be able to do:
ObjectBag<string> myBag = new ObjectBag();
myBag.Add<int>("testInt", 123);
myBag.Add<TestClass>("testClass", new TestClass();
myBag.TryGet<int>("testInt", out someInt);
myBad.TryGet<TestClass>("testClass", out someTestClass);
I don't want to use ref, as that requires initializing the variable before passing it in.