Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you copy a struct to another, when both are the same, unknown, type

Tags:

c#

struct

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;
    }
}
like image 558
Art Avatar asked Jan 25 '26 13:01

Art


1 Answers

You have a couple of mistakes in your code. Value types are copied when passed as arguments and returned from functions:

  1. In Add(ValueType _testData) the variable _testData will be a copy of the ValueType fields of the passed argument.

  2. _testData.GetType() will always return typeof(ValueType).

  3. _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;
    }
}
like image 97
Andrey Nasonov Avatar answered Jan 27 '26 02:01

Andrey Nasonov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!