Hello All,
Welcome to C# article, My Self Chakrapani Upadhyaya a full stack engineer.
In this article we will understand what is the difference between "the-ref-and-out-keywords".
ref:
Basically ref tells the compiler that the object is initialized before entering the function, ref is two-ways means The value is already set and The method can read and modify it.
And another good thing is....
A ref is a reference to a memory(ref) location of a variable. When we pass parameters by reference, a new storage location is not created for these parameters as like value parameters.
The reference parameters represent the same memory location as the actual parameters that are supplied to the method.
Note down this:
When you pass a value type such as int, float, double etc. as an argument to the method parameter, then it is passed by value.
So, if you modify the parameter value, it does not affect original argument in the method call.
But if you mark the parameter with “ref” keyword, then it will reflect in the actual variable.
Here is the simple demonstration...
Without ref:
int result = 20;
System.Console.WriteLine(GetMessage(result));
System.Console.WriteLine(result);
int GetMessage(int result){
result = 10*result;
return result;
}
Output:
Original variable value doesn't change, instead its created new memory location.
With ref:
int result = 20;
int GetMessage(ref int result){
result = 10*result;
return result;
}
System.Console.WriteLine(GetMessage(ref result));
System.Console.WriteLine(result);
Output:
In above example, a new storage location is not created for these parameters as like value parameters.