Search code examples
c#pass-by-referenceunsafe-pointers

Assign a reference of an integer in a class


Is it possible to pass an integer as reference at class initialization and safe the reference?

class Foo {
    private int _refVal;
    public Foo(ref int val) {
        _refval = val; // saves the value, not the reference
    }
}

I could use pointers, but then I need an unsafe context.


Solution

  • This is not possible.

    Instead, you can use a class with a writable property, like this:

    class Reference<T> {
        public T Value { get; set; }
        public Reference(T value) { Value = value; }
    }