Search code examples
c#structreadonlybyref

How to pass struct byref and readonly to a function in C#?


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.


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.