Search code examples
c#return-typeref

C#: How to return optional ref to struct


In C# how do I write a function that may or may not return a ref to a struct?

What I basically want is a return type Nullable<ref OutboxSlot> but the compiler complains about ref beeing an unexpected token.

I want to do is something like this:

Nullable<ref SomeFieldStruct> GetCorrectField(ref SomeStruct s) {
  // Depending on some property of s either return null or a ref to a field of s
}

In something like Rust I could easily declare a return type like Option<&mut SomeFieldStruct>.

PS: No I cannot use classes.


Solution

  • In project properties, in Compilation, you must check "Allow unsafe code":

    Allow unsafe code

    Don't forget set in Debug and Release.

    I'm going to use this structs:

    public struct SomeStruct
    {
        public int Value;
        public SomeFieldStruct Field;
    }
    
    public struct SomeFieldStruct
    {
        public double Value;
    }
    

    Then, create your method:

    public unsafe static SomeFieldStruct* GetCorrectField(ref SomeStruct s)
    {
        // Depending on some property of s either return null or a ref to a field of s
        if (s.Value == 0)
        {
            fixed (SomeFieldStruct* field = &s.Field)
            {
                return field;
            }
        }
    
        return null;
    }
    

    If Value is zero, you return the address of Field property of your struct. Check it:

    public unsafe static void Test()
    {
        SomeStruct obj;
        obj.Value = 0;
        obj.Field.Value = 1.2;
    
        SomeFieldStruct* field = GetCorrectField(ref obj);
        if (field != null)
        {
            field->Value *= 10.0;
        }
    }
    

    With pointers, you must use arrow -> instead of dot. All your unsafe methods must include unsafe keyword.