Question

Is it possible to pass a struct byref and readonly to a function? (just like T const& in C++)

struct A
{
    public int b;
}
void func1(ref A a)  // I want to make this `a` immutable
{

}

How to do that?

Update

My biggest concern is passing (1) immutable state (2) efficiently. Second concern is the mutating the state must be simple and easy as like mutable object.

Was it helpful?

Solution

Currently I am doing this like this. A kind of boxing.

class
ImmutableBox<T> where T : struct, new()
{
    public readonly T state;
    ImmutableBox(T state)
    {
        this.state = state;
    }
}

struct
ExampleStateA
{
    public string someField;
}

void
func1(ImmutableBox<ExampleStateA> passImmutableStateWithBox)
{
}

By keeping the instance of ImmutableBox<T>, I can pass immutable object with pointer copy, and it's still easy to edit State because State is mutable. Also I gain a chance to optimize equality comparison to pointer comparison.

OTHER TIPS

I dont think there is a way to make a ref parameter immutable. Instead, you should make your structs immutable in the first place to avoid side effects. Read more here:

Why are mutable structs evil

There is alas no concept of const ref in .NET. If the struct is small, you should pass it by value. If it's large, you must decide whether you want to trust the recipient of the struct not to modify it (in which case you can efficiently pass by ref) or put up with the inefficiency of passing by value.

Note that making structs pretend to be immutable will do nothing to help your problem, but will simply impair efficiency in cases where you want to modify part it. One should often avoid having struct methods which mutate the underlying struct since compilers try to fake "const ref" member invocation by silently converting pass-by-reference member invocation on read-only members to to pass-by-value, but there's no such problem with structs that expose fields.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top