What is the difference between ref and out keywords in C#? When do you use them?
  • both ref and out keywords are used to pass data between a caller and a callee methods.
  • ref keyword represents "call by reference" where the reference of a variable is passed from the caller method to the callee method.
  • It is used when the variable being passed is expected to be modified inside the called method.
  • out keyword is used when the called method needs to return more than one return values, since a method can return only one type.
  • a ref variable behaves like an in-out parameter where data can be passed into and out of the method
  • an out variable behaves like an out parameter where additional data is returned from the called method.
  • ref variable needs to be initialized in the caller method.
  • out variable needs to be assigned in the called method before returning to the caller method.
public void CallerMethod() {
  // needs to be assigned else compiler throws error
	int valueToBeReferenced = 10; 
	int valueToBeOutParamed;
  CalledMethodWithRef(ref valueToBeReferenced);
  CalledMethodWithOut(out valueToBeOutParamed);
}

void CalledMethodWithRef(ref int value) {
	// some modification
	// doesn't throw error
	// since it is assured that
	// value is not unassigned
	value += 10;
}

void CalledMethodWithOut(out int value) {
	// compulsory assignment
	value = 10;
}

C# Concepts •  Added 8 days ago

Join the Newsletter

Subscribe to get our latest content by email.
    We won't send you spam. Unsubscribe at any time.
    We use cookies to provide you with a great user experience, analyze traffic and serve targeted promotions.   Learn More   Accept