C# Methods

Pass by value or pass by reference

In C# you may choose how you want to pass a method’s variable.

by value example (default)

// by value
int number = 25;
PassByValue(number); 
Console.Write(number); // prints 25
public static void PassByValue(int number)
{
	// this won't take effect
	number = 12;
}

by reference example (out)

// by reference
int number;
PassByOutReference(out number);
Console.Write(number); // prints 12
public static void PassByOutReference(out int number)
{
	number = 12;
}

by reference example (ref)

// by reference (ref)
int number = -1;
PassByReference(out number);
Console.Write(number); // prints 12
public static void PassByRefReference(ref int number)
{
	number = 12;
}

out vs ref

(!) You should use out unless you explicitly need ref (!)

  • out doesn’t need the variable to be initialized first
  • ref needs the variable to be initialized first. This could confuse readers as it looks as if the initial values were relevant, but they’re not.

How to return 2 values from a function

We may do this by passing values by reference

public void Return2Values(out int number1, out int number2)
{
	number1 = 10;
	number2 = 20;
}

We also may do this through tuples (check as I have another example more in-depth)

public (int Number1, int Number2) Return2Values()
{
	return (10, 20);
}

String interpolation

We may Concat strings

string text1 = "test";
string text2 = "test2";
string textsJoined = string.Concat(text1, text2);

Or we may interpolate them

string text1= "test";
string text2 = "test2";
string textsJoined = $"{text1} something something {text2}";

There’s also a StringBuilder.

Local functions

You can make functions inside other functions. Local functions can only be executed and seen from the main function’s context.

class Program
{
	static void Main(string[] args)
	{
		MainFunction(12);
	}
	
	public static void MainFunction(int number)
	{
		number = number + 10;
		LocalFunction(number);

		void LocalFunction(int localNumber)
		{
			localNumber = localNumber * 15;
		}
	}
}

Default values

You may give default values to methods. Variables with default values, must be at the end.

public double Calculate(double a, double b, string operation = "add")
{
	switch(operation.ToLower()) 
	{
		case "add": return a+b;
		case "substract": return a-b;
	}
}

you invoke it as follows

var calc = new Calculator();
calc.Calculate(10, 5); // 15
calc.Calculate(10, 5, "substract"); // 5