Search code examples
c#reference

C# pass a parameter a variable with changing references


I have the following code snippet as an example of what I want to do. In this example I would like to print "reference1".

var reference1 = new TestValueClass() { AValue = "reference1" };
TestValueClass myPointer = null;
var useClass = new TestPointerUsage(myPointer);
myPointer = reference1;
Console.WriteLine(useClass.testValueClass.AValue);

I fully understand why it isn't working, because in the 3rd line it takes the reference of myPointer, that is currently "null" and stores that internally.

Is in C# any concept of passing a reference to the pointer to an object, instead of the object itself?

The most simple solution for this would be to pass an object that have inside the pointer, but I want to check from time to time if other solutions are also possible.

Thanks


Solution

  • Think about what would happen if myPointer goes out of scope, but the instance of TestPointerUsage still exists. What would useClass.testValueClass refer to?

    What you want is possible if TestPointerUsage is a ref struct. A ref struct can only live on the stack and cannot escape to the heap, so the situation above cannot occur.

    A ref struct can have ref fields, and that is what testValueClass should be.

    public ref struct TestPointerUsage {
        public ref TestValueClass? testValueClass;
        
        public TestPointerUsage(ref TestValueClass? testValueClass) {
            this.testValueClass = ref testValueClass;
        }
    }
    
    public class TestValueClass {
        public required string AValue  { get; init; }
    }
    

    The following code would print "reference1":

    var reference1 = new TestValueClass { AValue = "reference1" };
    TestValueClass? myPointer = null;
    var useClass = new TestPointerUsage(ref myPointer);
    myPointer = reference1;
    Console.WriteLine(useClass.testValueClass?.AValue);