alhazen alhazen - 3 months ago 9
C# Question

Variable assignment that updates reference?

I searched quite a bit but found no answer.

This is what I have:

Wrapper _wrap1;
Wrapper _wrap2;

public Wrapper GetWrapper(int num)
{
Wrapper cachedWrapper = num == 1 ? _wrap1 : _wrap2;
if(cachedWrapper == null)
{
cachedWrapper = new Wrapper();
}

return cachedWrapper;
}


I'm aware that '
cachedWrapper
' is a new reference, and will have no impact on either
_wrap1
or
_wrap2
.

I'm searching for an elegant way that will update those fields without the need for an additional if-statement.

My class has a lot more than just 2 Wrappers, and I have more types than just 'Wrapper'.

Thanks

Answer

There isn't a way to do precisely what you're asking.

But, adding to Blorgbeard's comment, you can use a dictionary:

using System.Collections.Concurrent;

ConcurrentDictionary<int, Wrapper> wrapperDictionary;

public Wrapper GetWrapper(int num)
{
    return wrapperDictionary.GetOrAdd(num, _ => new Wrapper());
}