Methods

Intro

Methods are useful because:

  • Reuse of code / Reduces redundancy
  • Impoves readability
  • Better extendable
  • Better debugging
  • Much more..

Let us look again at the example from the Rocket-Launch

using System;
namespace Christian {
    class Methods {
        static int AddTwoNumbers(int num1, int num2) {
            return num1 + num2;
        }
        static void Main() {
            Console.WriteLine( AddTwoNumbers(5, 7) );
        }
    }
}

Line 4, 7: Method Head containing:

  • static: A method-modifier
  • void / int: Return-Type of methods
  • AddTwoNumbers / Main: Name of methods
  • () / (int num1, int num2): Parameters

Let us write that down with placeholders:

<access> <modifier> <return type> <name> (parameter list) {
   // Some Method Code  BODY
}
  • Access: If we do not explicitly declare an access specifier, the default access will be used. Let's leave it by that for now.
  • Modifier: We always use static and again we leave it by that, until we talk about classes. Please notice that there are also other method modifiers we are not worrying about for now.
  • Return Type: This determines which datatype the return type has to be.
  • Name: The name to call the function, we should use "upper cammel case". Please check this, if you are not familiar with that term.
  • Parameter List: We can specify parameters, which can be passed to the method.

Example

of a Method that prints all values of an integer array. The method has no return type (if the method returns no value, we use "void" as datatype (empty datatype).

static void Main(string[] args) {
    int[] arr01 = { 2, 5, 7 };
    PrintArray(arr01);
}
static void PrintArray(int[] array) {
    for (int i = 0; i < array.Length; i++) {
        Console.Write(array[i] + " ");
    }
}

Output:
2 5 7

Paradox of empty datatype

Warning! Please only check this out, if you are not already confused enough!!

It is a little paradox, that if we do not want any data passed to a method when calling we use the empty parentheses.

But if we want no data to be returned from the method we use the datatype void.

In the language C that was not the case, there you had to put void inside the parentheses to indicate that no values are passed to the function.

I like the C approach, because it is consitent. But I understand to make code easier to read and write we abandoned that.

Example

In this example the method TrippleValue() is passed a value of type integer and it returns a result of type integer.

static void Main(string[] args) {
    int tripple = TrippleValue(7);
    Console.WriteLine(tripple);
}
static int TrippleValue(int num) {
    return num * 3;
}

Reminder to myself and you: Please try to never name a variable "result" or "value".

Optional Paramter

The above Code would not work, if we do not pass a value to the mehtod:

static void Main(string[] args) {
    int tripple = TrippleValue(); // Error !
    Console.WriteLine(tripple);
}
static int TrippleValue(int num) {
    return num * 3;
}

Line 2: Error because the method-call requires an argument.

Make it work:

We can define an optional paramter. If the method is called without an argument, the optional value will be used by the method.

static void Main(string[] args) {
    int tripple = TrippleValue(); // Works
    Console.WriteLine(tripple);
}
static int TrippleValue(int num = 5) {
    return num * 3;
}

Output:

15

Overloading Methods

Overloading means, that we declare mutliple Methods with the same name. Those methods have different parameter. So a method with the same name ca be called by using different types of data:

static void Main(string[] args) {
    int trippleNum = TrippleValue(3); // Calls Method in Line 7
    Console.WriteLine(trippleNum);
    string trippleText = TrippleValue("test "); // Calls Method in Line 10
    Console.WriteLine(trippleText);
}
static int TrippleValue(int num) {
    return num * 3;
}
static string TrippleValue(string text) {
    return (text+text+text);
}

Output:

9
test test test

Different types of parameters

  • in-Parameter
  • out-Parameter
  • ref-Parameter

Until now we only worked with th in-Parameter

To use an in-Parameter we use no additional keyword, it is the default case.

If a method uses in-Parameters, the method will use a copy of the value and the original variable will not be changed.

Example

static void Main(string[] args) {
    string txt01 = "original Text";
    Console.WriteLine(txt01);
    ChangeText(txt01);
    Console.WriteLine(txt01);
}
static void ChangeText(string text) {
    text = "This is my text";
}

Output:

original Text
original Text

So the ChangeText() Method does not change the original value.
If we would like to change the value of txt01, we can use an out- or ref-parameter.

Example ref-Parameter

static void Main(string[] args) {
    string txt01 = "original Text";
    Console.WriteLine(txt01);
    ChangeText(ref txt01);
    Console.WriteLine(txt01);
}
static void ChangeText(ref string text) {
    text = "This is my text";
}

Output:

original Text
This is my text

Line 4: When calling a method, that uses ref-Parameters, we have also to use the ref-keyword in the call-instruction.

Line 7: Declaring a ref-Parameter.

Example out-Parameter

The out-Parameter works and acts pretty much the same when first looking at it. I just changed the ref-keywords to out-keywords

    class Program {
        static void Main(string[] args) {
            string txt01 = "original Text";
            Console.WriteLine(txt01);
            ChangeText(out txt01);
            Console.WriteLine(txt01);
        }
        static void ChangeText(out string text) {
            text = "This is my text";
        }
    }

One of the differents however is, that we do not have to initalize an out-parameter variale outside of the method before calling.

static void Main(string[] args) {
            //string txt01 = "original Text";
            //Console.WriteLine(txt01);
            string txt01;
            ChangeText(out txt01);
            Console.WriteLine(txt01);
        }
        static void ChangeText(out string text) {
            text = "This is my text";
        }

This example would not work, if we use the ref-keyword.

The use of this, is that via return type, we can only return one variable.
By using ref and out we can kind of simulate multiple return values.

Recursion

Recursive vs. Iterative Problem Solving

Both ways solve the same problems: If we can solve a problem in an iterative way, we can also solve the same problem by help of a recursive solution.

Example: Print Numbers from 1 to a value given in parameter on console

Iterative Way:
static void Print(int max) {
    for (int i = 1; i < max; i++) {
        Console.WriteLine(i);
    }
}
Recursive Way:
static void Print(int max) {
    int start = 1;
    Console.WriteLine(PrintIterative(start, max));
}
static int PrintIterative(int st, int ma) {
    if (st == ma) {
        return st;
    }
    else {
        Console.WriteLine(st);
        return PrintIterative(++st, ma);
    }
}
Recursion
Please ask you Professor if this is part of the learning matter if you are in the first semester.

Recursion, simply said, happens when a method calls itself.

We can differ between direct recursion and indirect recursion.

Recursion is usually a good way to go when coding divide and conquer algorithms.

How to solve problems by recursion

Description Keybinding (english layout!)
Autogenerate Method Write the function call, Strg + . , Enter