Skip to content

Parameters

Mario Gutierrez edited this page Jan 7, 2017 · 1 revision

Modifiers

  • out - method must assign a value to the argument before returning. Not necessary for caller to initialize variable.
  • ref - method may assign a value to the argument. Necessary for caller to initialize variable.
  • params - list of parameters.
Example 1 (out)
void Add(int a, int b, out int sum)
{
  sum = a + b;
}
int sum;
Add(4, 5, out sum);
Example 2 (ref)
void Swap(ref Card a, ref Card b)
{
  Card tmp = a;
  a = b;
  b = tmp;
}
Card a = new Card("KD");
Card b = new Card("9D");
Swap (ref a, ref b);
Example 3 (params)
int Sum(params int[] nums)
{
  int sum = 0;
  foreach (int i in nums)
  {
    sum += i;
  }
  return sum;
}
int result = Sum(1, 2, 3, 4);

Default Parameters

void LogEvent(string msg, string tag = "Default", Color color = Color.blue);

You can use named parameters to feed arguments out of order.

LogEvent(tag: "Timing");

Unnamed, ordered parameters must come first though.

LogEvent(msg, color: Color.red);

You can also use default parameters in constructors above .NET 4.0.

Clone this wiki locally