ValueType ref return from List or Dictionary, Workarounds?

Viewed 19

I'm working in a new C# codebase where they use structs heavily. I've done a lot of C# but not too much with structs. (I always tried to avoid them after reading this type of stuff: Why are mutable structs “evil”?)

Most of the issues that I have run into are from accidentally copying a struct when I really want to get a reference to an existing struct. Functions that return ref and using ref to get values out of arrays of structs are very useful for avoiding copying.

But what is a good solution for storing structs in a list or dictionary and getting a reference out of those? There appears to be no equivalent of a ref return for arrays. Am I missing a way to do this?

As a workaround, I have taken to creating a container class for structs like in the code below. Is there any alternative? Also, is there some generic value type wrapper class built into C# that I should be using for each of these instead of defining my own? Some sort of IValueTypeWrapperForContainers?

struct MyStruct
{
    public int foo;
}

class MyClass
{
    public MyStruct ms;
    public MyClass()
    {
        ms = new MyStruct();
        ms.foo = 42;
    }
}

This does not change the value of 42 because ms1 is a copy of the struct:

Dictionary<DateTime, MyStruct> timeStructMap = new Dictionary<DateTime, MyStruct>();
MyStruct ms = new MyStruct();
timeStructMap.Add(DateTime.Today, ms);

var ms1 = timeStructMap[DateTime.Today];
ms1.foo = 43;

This does what I want instead.

Dictionary<DateTime, MyClass> timeClassMap = new Dictionary<DateTime, MyClass>();
MyClass mc = new MyClass();
timeClassMap.Add(DateTime.Today, mc);

var mc1 = timeClassMap[DateTime.Today];
mc1.ms.foo = 43;
0 Answers
Related