Skip to content

Passing Ref Struct by Reference or By Pointer? #100703

Answered by jkotas
Chacoon3 asked this question in Q&A
Discussion options

You must be logged in to vote

The internal mechanism is the same. The code quality difference between the two are negligible.

The main differences for ref structs is in safety guardrails. Passing by reference is safe concept. The C# compiler is going to report error if the code attempts to create a dangling pointer. For example, the following example is going to produce compiler error:

ref int M(ref int x)
{
    int x = 1;
    return ref x;
}

However, the equivalent code with unsafe context and pointers is going to compile fine, and it is likely going to crash at runtime due to the severe lifetime bug.

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
1 reply
@Chacoon3
Comment options

Answer selected by Chacoon3
Comment options

You must be logged in to vote
1 reply
@Chacoon3
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants