Difference between ref and out keywords in C#

ref and out are pretty much like the pointers as in C/C++, they deal with the memory location of the object instead of the object directly.

Mostly ref and out keywords are used in the method’s parameters/arguments.


void myFunction(ref Student obj);

ref means that the value in the ref parameter is already set, the method can read and modify it.
Using the ref keyword is the same as saying that the caller is responsible for initializing the value of the parameter.

ref keyword must be there in method declaration/definition signature as well as method calling signature.

void FunctionByRef(ref Student obj)

Student s = new Student("Farhan");

FunctionByRef(ref s)

Here, FunctionByRef can read and modify the content of the original object s.


void FunctionByOut(out Student obj);

out tells the compiler that the initialization of an object is the responsibility of

the function, the function has to assign to the out parameter.

It’s not allowed to leave it unassigned. 

out means that the value of the argument isn’t set and the method must set it

before return and couldn’t read before setting value.

out parameter does not have to be explicitly initialized before being

passed and any previous value will be overwritten.

void FunctionByOut(out Student obj)

Student s;

void FunctionByOut(out s);

Here, FunctionByOut must assign some value to the argument, or the program will not compile.

IMPORTANT NOTE: You cannot overload two methods whose signature difference is the only ref and out in parameters. it will be a compile-time error.