Home > Net >  Passing a reference to a value in a struct in C# 11
Passing a reference to a value in a struct in C# 11

Time:12-28

I'm unable to pass a reference to a value in a struct in C# 11. How do I do it?

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object. at CustomRef..ctor(Double& number) in path\Program.cs:line 17 at Program.$(String[] args) in path\Program.cs:line 4

using System.Runtime.CompilerServices;

var x = 1.1;
var myTuple = new CustomRef(ref x);

x = 2.2;

Console.WriteLine(x); // Outputs 2.2
Console.WriteLine(myTuple.GetNumber()); // Outputs 2.2

public ref struct CustomRef
{
    private readonly ref double _number;

    public CustomRef(ref double number)
    {
        _number = number;
    }

    public double GetNumber()
    {
        if (Unsafe.IsNullRef(ref _number))
        {
            throw new InvalidOperationException("The number ref field is not initialized.");
        }

        return _number;
    }
}

CodePudding user response:

You need to assign ref field using ref modifier:

public CustomRef(ref double number)
{        
    _number = ref number; // < note ref here
}

Here is github issue with some discussion about this situation (and why compiler even allows you to do this).

  • Related