Skip to main content

  | मौसम…

411 समाचार
Public archive edition · Attributed source reporting with original dates · AI drafts are excluded

411 REFERENCE · Wikibooks

C Sharp Programming/Keywords/ref

Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.

Keywords ref __TOC__ The ref keyword explicitly specifies that a variable should be passed by reference rather than by value. A developer may wish to pass a variable by reference particularly in case of value types. If a variable is passed by reference, only a pointer is sent to a function in reality, reducing the cost of a method call in case it would involve copying large amounts of data, something C# does when normally passing value types. Another common reason to pass a variable by reference is to let the called method modify its value. Because this is allowed, C# always enforces specifying that a value is passed by reference even in the method call, something many other programming languages don't. This let developers reading the code easily spot places that can imply a type has had its value changed in a method, which is useful when analyzing the program flow. Passing a value by reference does not imply that the called method has to modify the value; see the out out keyword for this. Passing by reference requires the passed variable to be initialized. An example of passing a variable by reference follows: void CallingMethod() { int i = 24; if (DoubleIfEven(ref i)) Console.WriteLine("i was doubled to {0}", i); // outputs "i was doubled to 48" } bool DoubleIfEven(ref int iValue) { if (iValue%2 == 0) { iValue *= 2; return true; } return false; }