Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing a reference to a value in a struct in C# 11

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;
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading