C# 03 Study Notes Methods and Scope
3. Methods and Scope
3.1. Create Method
📌return
at the end of method
The return
keyword is at the end of the method which return the return type of a method.
//int function
int addValues(int lhs, int rhs)
{
return lhs + rhs;
}
//void function
void sayHello()
{
Console.WriteLine("Hello world!");
return;
}
⭐️ It is recommended that return nothing at the end of a void
function.
📌expression-bodied method
Such design of programming language is called syntactic sugar which simplify the code and improve readability.
xxxxxxxxxx
int addValues(int lhs, int rhs) => lhs + rhs;
void sayHello() => Console.WriteLine("Hello world!");
📌return multiple values
This is only supported by VS 2017 and above which you have to install System.ValueTuple
xprivate (int, int) divide(int lhs, int rhs)
{
int division = lhs / rhs;
int remainder = lhs % rhs;
return (division, remainder);
}
3.2. Scope
📌What is the lifetime of a variable?⭐️⭐️⭐️
The born of a variable starts from where it is declared and it ends after the method is finished.
📌What is a scope?
The scope of a variable is simply the region of the program in which that variable is usable. (inside the bracket{}
)
📌local variable
The variable inside the bracket{}
of a method is local variable.
❌
xxxxxxxxxx
void myMethod()
{
string myName = "";
}
void yourMethod()
{
myName += "Angela"; //ERROR!! myName is a local variable
}
✔️
xxxxxxxxxx
void myHello()
{
string myName = "Daniel";
Console.WriteLine($"{myName} said hello.");
}
void yourHello()
{
string myName = "Theresa";
Console.WriteLine($"{myName} said hello.");
}
📌field(global variable)
In C#, they name the global variable as field. ("字段" in Chinese)
xxxxxxxxxx
class Example
{
int count; //global variable
void setZero() => count = 0;
void addValue(int num) => count += num;
}
📌overloaded method
In short, a method with:
- same return type and same name
- different input parameters
A nice example we can take a look at RhinoCommon
methods.
xxxxxxxxxx
//Create twin curves
public static Curve[] CreateTweenCurves(Curve curve0, Curve curve1, int numCurves)
public static Curve[] CreateTweenCurves(Curve curve0, Curve curve1, int numCurves, double tolerance)
The return type is an array of curve: Curve[]
But the parameters can't be different.
📌Refactoring code⭐️⭐️⭐️
This is holly important and useful!! Suppose you have an average method which does:
- 1️⃣sum up all the numbers
- 2️⃣take the average
xxxxxxxxxx
double average(double[] numbers)
{
double sum;
int amount;
double average;
sum = numbers.Sum();
amount = numbers.Length;
average = sum / amount;
return average;
}
Select the code you want to extract as a smaller method / helper method.
You can extract them into:
xxxxxxxxxx
double average(double[] numbers)
{
double sum;
int amount;
double average;
sum = OperationSum(numbers);
amount = numbers.Length;
average = OperationDivide(sum, amount);
return average;
}
private static double OperationDivide(double sum, int amount)
{
return sum / amount;
}
private static double OperationSum(double[] numbers)
{
return numbers.Sum();
}
3.3. Nested Method
📌Why should we use Nested Method?
Big Picture⭐️: For those help methods which are called only by one main method, must be encapsulated.
📌Example
Suppose a function is:
xxxxxxxxxx
long calculateFactorial(string input)
{
}
The input is string
and it must be parsed into numbers for operation. Apparently, it also demand a real factorial method for number operation. Hence the design should be:
xxxxxxxxxx
long calculateFactorial(string input)
{
//1. Parse to number
//2. Declare a factorial method
//3. Run the factorial method and return value
}
The result:
xxxxxxxxxx
long calculateFactorial(string input)
{
//1.
int number = int.Parse(input);
//2.
long factorial(int num)
{
if (num == 1)
{
return 1;
}
else
{
return num * factorial(num - 1);
}
}
//3.
long result = factorial(number);
return result;
}
3.4 Optional and Named Parameters
📌What is Optional Parameter?
In short, the parameter defined inside the bracket()
has default value.
xxxxxxxxxx
void ransac(double[] input, int seed=1, string mode="default");
The later 2 parameters are optional.
⚠️🚨 Optional parameters must be declared after mandatory parameters.
xxxxxxxxxx
void ransac(numbers);
void ransac(numbers, 2);
void ransac(numbers, "super");
📌What is Named Parameter?
In short, it explicitly assigns the variables.
xxxxxxxxxx
void ransac(numbers, mode:"super", seed:2);
void ransac(seed:2, mode:"super", input:numbers);
If the arguments are explicitly assigned, they can be in arbitrary position.
📌Dangerous and Bad Habit🚨
The following one can be tricky!
xxxxxxxxxx
void Method(int first, double second=0.0, string third="Hello");
void Method(int first, double second=1.0, string third="Goodbye", int fourth=100);
when you type:
xxxxxxxxxx
Method(1, 2.5);
The compiler does not know whether to use which method since the beginning of them are the same! I personally don't like the overloaded function with similar parameters and default value.