Use of REF keyword in a method? C# | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
0

Use of REF keyword in a method? C#

is the ref keyword used only to return values of void methods, wich aren't supposed to return any value?! or is my statement wrong?

12th Mar 2018, 11:02 PM
MajorSam
MajorSam - avatar
3 Antworten
+ 3
ref keyword is used when we want to affect passed variable to a method. static void Change(ref int x) { x = 2; } static void Main(string[] args) { int a = 3; Change(ref a); Console.WriteLine(a); //outputs 2 } There is nothing to do with method return type - it can be int, bool... - it doesn't matter.
12th Mar 2018, 11:52 PM
Vladi Petrov
Vladi Petrov - avatar
+ 1
Ref is used to pass in a reference to an object. This means it will edit that object directly. For instance, if you pass in an integer and perform some calculations that change the value of the integer, the integer’s value will be changed to the new value in the function that called it. If you know c++ or c, it’s like the references or pointers in those languages.
12th Mar 2018, 11:50 PM
Ariela
Ariela - avatar
0
got it, thanks guys!
12th Mar 2018, 11:54 PM
MajorSam
MajorSam - avatar