Here is my first attempt. I hoped that the last statement in Fill() would do a memberwise copy, but in fact nothing happened. The issue is doubtless that the types in the assignment are not known at compile time. My intent is to use a dictionary of structs, keyed by type, in connection with unit tests. Maybe it can't be done, without adding knowledge of the various individual structs to my class.
internal class TestData
{
private static Dictionary<Type, ValueType> mTestData = new Dictionary<Type, ValueType>();
internal static void Add(ValueType _testData)
{
mTestData.Add(_testData.GetType(), _testData);
}
internal static void Fill(ValueType _runtimeData)
{
ValueType testData = mTestData[_runtimeData.GetType()];
_runtimeData = testData;
}
}
You have a couple of mistakes in your code. Value types are copied when passed as arguments and returned from functions:
In Add(ValueType _testData) the variable _testData will be a copy of the ValueType fields of the passed argument.
_testData.GetType() will always return typeof(ValueType).
_runtimeData = testData; modifies the local variable _runtimeData but it cannot modify the passed argument.
Reconsider using generics and boxing value types. Here is the working modification of your code
internal class TestData
{
private static Dictionary<Type, object> mTestData = new Dictionary<Type, object>();
internal static void Add<T>(T _testData) where T: ValueType, struct
{
mTestData.Add(typeof(T), _testData);
}
internal static void Fill<T>(ref T _runtimeData) where T: ValueType, struct
{
T testData = (T)mTestData[typeof(T)];
_runtimeData = testData;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With