Help me explain the ref keycode
Hello guys, I'm new to c# , so sorry if I ask a dumb question
I have just read about keycode ref and it's said that It's needed to return a value from a method
But in this w3s tutorial they don't need ref to return the value, just need to call the method by replacing the value in the parameters
using System;
namespace MyApplication
{
class Program
{
static void MyMethod(string fname)
{
Console.WriteLine(fname + " Refsnes");
}
static void Main(string[] args)
{
MyMethod("Liam");
MyMethod("Jenny");
MyMethod("Anja");
}
}
}
This is the ref tutorial on windows
using System;
namespace ref_keyword {
class GFG {
// Main Method
static void Main(string[] args)
{
// Initialize a and b
int a = 10, b = 12;
// Display initial values
Console.WriteLine("Initial value of a is {0}", a);
Console.WriteLine("Initial value of b is {0}", b);
Console.WriteLine();
// Call addValue method by value
addValue(a);
// Display modified value of a
Console.WriteLine("Value of a after addition"+
" operation is {0}", a);
// Call subtractValue method by ref
subtractValue(ref b);
// Display modified value of b
Console.WriteLine("Value of b after "+
"subtraction operation is {0}", b);
}
// Define addValue
// Parameters passed by value
public static void addValue(int a)
{
a += 10;
}
// Define subtractValue
// Parameters passed by ref
public static void subtractValue(ref int b)
{
b -= 5;
}
}
}
Can someone explain this in a simple way to me, I feel really dumb
13 Replies
To understand
ref
first you need to understand passing by value and passing by reference
When you write a method that takes a value type like int
as an argument, its normally passed by value which means a copy of the value is made and sent to the method
So if the method changes the value, the original variable is not changed
If you add the ref keyword, that changes and the original variable will be changedSo in short, ref changes the variables itself , and without ref the variables in Main() is not changed ?
correct
ah, thank you
Pobiega
REPL Result: Success
Console Output
Compile: 462.537ms | Execution: 41.919ms | React with ❌ to remove this embed.
also note how you must add the
ref
keyword when you call the ref method, to make it very clear that your variable might changeBe noted that, it's applicable to values that follow copy trait, like numbers. But you don't need
ref
for reference values like objects, classes or collections.yeah. reference types are always passing by reference
Passing reference types via
ref
enables the method to reassign the original variable though, so it's not like it's only used for value types.fair point, but thats a pretty rare need
Arguably.
For a good example one might look at the TryXXX pattern
.. huh?
that uses
out
not ref
Hm you're right. I guess it's more rare to have reference type
ref
params than my intuition wanted me to believe :catshrug: