C# 03 Study Notes Methods and Scope

C#

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.

⭐️ 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.

 

📌return multiple values

This is only supported by VS 2017 and above which you have to install System.ValueTuple

 

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.

✔️

 

📌field(global variable)

In C#, they name the global variable as field. ("字段" in Chinese)

 

 

📌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.

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

Select the code you want to extract as a smaller method / helper method.

You can extract them into:

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:

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:

The result:

 

3.4 Optional and Named Parameters

📌What is Optional Parameter?

In short, the parameter defined inside the bracket() has default value.

The later 2 parameters are optional.

⚠️🚨 Optional parameters must be declared after mandatory parameters.

 

📌What is Named Parameter?

In short, it explicitly assigns the variables.

If the arguments are explicitly assigned, they can be in arbitrary position.

 

📌Dangerous and Bad Habit🚨

The following one can be tricky!

when you type:

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.

 

Previous
Previous

C# 04 Study Notes Decision Statement

Next
Next

VR# What's Real About Virtual Reality?