Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

ref, out and in

in C#

Steven Giesel
ref
Passes the argument by reference, allowing the
method to read and modify the value. The
variable must be initialized before being passed.
ref
It also changes the semantics if you use ref with
a reference type like a string or a List<T>. In the
method below if you would not use the ref
modifier, “myString” would still be “Original
String” after the call due to the immutability of
string.
out
Similar to ref, but the variable doesn't need to be
initialized before being passed. The method must
assign a value before it returns.
out
You find this typical with the “Try” pattern where
the return value is a boolean type and the value
gets passed via out to the caller.
in
Passes the argument by reference, but the
method can only read the value, not modify it.
Useful for performance when passing large
structs.
Summary
Use ref when you want to allow a
method to read and modify a valu

Use out when you want a method to


initialize and return a value

Use in when you want to pass a large


struct by reference without allowing
modifications.

You might also like