MrDave1999 / SimpleResults

A simple library to implement the Result pattern for returning from services
https://mrdave1999.github.io/SimpleResults
MIT License
105 stars 2 forks source link

Why not use `ref struct` to represent the results? #64

Closed MrDave1999 closed 8 months ago

MrDave1999 commented 8 months ago

According to the official documentation: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/ref-struct

You can use the ref modifier in the declaration of a structure type. Instances of a ref struct type are allocated on the stack and can't escape to the managed heap.

If the Result, Result{T} or ListedResult{T} types are declared as "ref struct", polymorphism cannot be used. This library uses it to convert the result object to HTTP status code using the action filter or extension methods.

This has limitations, "ref struct" cannot implement an interface or do boxing.

Consider this example:

public class Program
{
     public static void Main()
     {
       Result result = Result.Invalid();
       object value = result; // There is a compilation error.
       var objectResult = new BadRequestObjectResult(value);
     }
}

This code does not compile, since if the Result type is a "ref struct", a boxing cannot be applied, i.e., converting the value type to a System.Object. If the compiler allowed this operation, the struct would escape into the heap and be managed by the garbage collection (GC).