I made a function and I was to pass array of strings in it like string[] aa= null
In function definition I made some update in it and then I found that its value was not updated when function was executed/returned .I am unable to understand which things in C# we are required to mention ref keyword . Doesn’t it always pass parameters by reference why need to mention ref ? which are the objects which require to be mentioned with ref in order to pass by reference ?
Code was like this ,just trying to show what was I doing,I was unable to update value without use of ref .
string[] temp = null
foo(ref temp);
//function definition
void foo (ref string[] temp)
{
temp = {"Hello World ","You must be updated now"}
}
foreach(string s in temp)
System.Console.WriteLine(s)
First, you’re pseudo code should work. But, before we get to that, there are three things at play here: value types, reference types, and the “ref” keyword.
Value types are typically your simple basic types like int, double, etc. string is a weird one as it is considered a value type.
More complex types, such as arrays and classes are reference types.
When you pass value types like ints and doubles then you are passing a copy of the value so if you pass int x = 10 into a method a change to x in the method won’t be reflected once you leave the method. On the other hand, if you pass MyClass class1, any changes to the properties within class1 will be reflected outside the function. Just don’t try to new up a new class1 inside your method because that won’t change outside the caller.
If you want to change a value type within a method, you pass by ref. If you want to new up a new class or array, then you pass by ref.
One more thing: it’s not that black-and-white between using out vs. ref. You would use out only if the design for the method was to always create your class or array only inside the method. You would use ref on a reference type if you wanted to allow the possibility to create a new object. Like,
Finally, if this is your actual code:
Later:
Then, it should actually work.