vimwiki

C# Methods

Declaration

access_modifier return_type MethodName(parameter_list)
{
    // method body
}
public string MyMethod(int x, string test)
{
    // method body
}

Expression bodied methods

static int Add(int x, int y)
{
  return x + y;
}

static void PrintUpper(string str)
{
  Console.WriteLine(str.ToUpper());
}

// The same methods written in expression-body form.
static int Add(int x, int y) => x + y;

static void PrintUpper(string str) => Console.WriteLine(str.ToUpper());

Lambda expression

parameter_list => expression

Here a lambda expression is past into the .Exists method as second parameter.
This method call the lambda exp for each number n in the array and return true if any of those are equal to 10.

Array.Exists(numbers, (int n) => {
  return n == 10;
});

shorter lambda

Array.Exists(numbers, n => {
  return n == 10;
});

Method overloading

public int Add(int x, int y)
{
    return x + y;
}

public double Add(double x, double y)
{
    return x + y;
}

public int Add(int x)
{
    return x + x;
}

Alternatively, this below would set a “default” value for y of 2 if only one argument is specified

public int Add(int x, int y = 2)
{
    return x + y;
}

out parameter

public bool Divide(int dividend, int divisor, out int quotient, out int remainder)
{
    quotient = dividend / divisor;
    remainder = dividend % divisor;
    bool divided = true;
    return divided; 
}