0
What is the different between "ref" and "out" keywords?
Hello, Both keyword are can be used optional for parameters. One need a variable to declare and initialize (ref) and the other just need to be declare (out). What I don't understand what exactly they do. A method know the memory Adress of an variable right. So can I use "out" to handles more safety variable. It looks like I initialize all variable in the moment I call the method. And I change the value of the variable. With "ref" it looks like I just "work" with an variable but don't want to change the value.
1 Resposta
+ 2
The above answer is correct. Both are used for "passing by reference", the only difference is initialization.
But the answer kind of misses the point. it seems like the person who's asking the question is mixing them up with pass by value and pass by reference. There's of course https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref#passing-an-argument-by-reference.
Meaning:
"With "ref" it looks like I just "work" with an variable but don't want to change the value."
is NOT correct.
When you "pass by value", the method consults the variable, copies the value of the variable and does whatever it needs to do with that value. However, afterwards the variable will still have the original value. In this case, to use the words of the questioner, the method does not know/care about the memory location of the variable. It doesn't change the variable.
When you "pass by reference", the method consults the variable, the variable points (refers) to the memory location, the method does what it needs the do with whatever it finds on that location. So if the method changes something, the value of the initial variable is also changed.
Ergo
"With "ref" it looks like I just "work" with an variable but don't want to change the value."
NOT CORRECT.
There are 3 video tutorials who van help you getting through
(i) pass by value/pass by ref
(ii) ref
(iii) out.
(i): https://www.youtube.com/watch?v=HOD8T2wJj1s&list=PLhq7kqloVlM95ROEbGpJEdpadDmtrC343&index=42
(ii): https://www.youtube.com/watch?v=Rf5LPKGFvj8&list=PLhq7kqloVlM95ROEbGpJEdpadDmtrC343&index=43
(iii): https://www.youtube.com/watch?v=qqD7lqfCBeM&list=PLhq7kqloVlM95ROEbGpJEdpadDmtrC343&index=44
Please support the creator of the videos and let his ads play (I do not know him).
Take care and good luck.