"Programming isn't about what you know; it's about what you can figure out.” - Chris Pine. When we do the same thing every day without any progression, after a while we might get bored or might be less productive. In programming we use methods(called also functions)to avoid code repetitions. Let's start learning c# methods.

C# Methods

A method is a block of code. The important thing is to call the method because a method runs when it is called. Actually during my recents posts, we were prety familiar with a lof of methods; for instance: indexOf(), Add(), WriteLine(), ReadLine() etc.

class MyFirstProgram
{
  static void Main(string[] args){

      MyMethod(); // In this line, we call MyMethod()

  }


  static void MyMethod() // is the name of method
  {
     // void means that MyMethod does not return ant value. 
     //  static is an access identifier.
    
  }
}
  • MyMethod() is the name of method.
  • void means that MyMethod does not return ant value.
  • static is an access identifier.
  • *MyMethod() // In this line, we call MyMethod().

How to define which data types a method run?

Suppose that we need a method that return the sum of all entered numbers. So, we need to return an int. Before writing SumMethod, we wrote int that indicates the type of output. Actually the returned value is depend on your needs.

  static int ThisMethodReturnsInt() 
  {
      // your codes
  }

    static int ThisMethodReturnsString() 
  {
      // your codes
  }

    static Float ThisMethodReturnsFloat() 
  {
      // your codes
  }
  
    static Float ThisMethodReturnsDouble() 
  {
      // your codes
  }

      static int[] ThisMethodReturnsDouble() 
  {
      // your codes
  }

SumMethod

You can find explanations in the code as a comment.

class MyFirstProgram
{
  static void Main(string[] args){

      int sum = SumMethod(10,20,30); // 10, 20, 30 are parameters.
      Console.WriteLine(sum);
  }

//
  static int SumMethod(int number1, int number2, int number3) // takes three parameters
  {
     
     return number1+number2+number3;// return the sum as a int
     // void means that MyMethod does not return ant value. 
     //  static is an access identifier.
    
  }
}

Exercise 1

Write the method which calculates square of entererd numbers.

class MyFirstProgram
{
  static void Main(string[] args){

      int sqrt = SqrtMEthod(5);
      Console.WriteLine(sqrt);
  }
  static int SqrtMethod(int n1) 
  {
     return n1*n1;
  }
}

Exercise 2

Write the method that adds 18% VAT to the price entered to it and returns it

static double KdvliFiyat( double s1)
{
    double kdv = (s1 * 0.18d);
    return s1 + kdv;
}

Exercise 3

Write the method that adds 18% VAT depending on the type of products to the price entered to it and returns it.

static double KdvliFiyat(string type, double s1)
{
    double result = s1;
    double kdv;
    if (type == "food")
    {
       kdv = (s1 * 0.08d);
    }
    else if (type == "education")
    {
        kdv = (s1 * 0.05d);
    }
    else
    {
        return KdvliFiyat(s1);
    }
    result += kdv;
    return result;
}

Exercice 4

Write the method that calculates the factorial of a number.

static int factorialCalculator(int s1)
{
            
    if (s1 == 1)
    {
        return s1;
    }
    else
    {
        return s1 * faktorielCalculator(s1 - 1);
    }
}

Exercise 5

After getting one number from the user, we return true if it's a prime number.

static bool IsPrime(int s1)
{
    if (s1== 2)
    {
        return true;
    }
    for (int i = 2; i < s1; i++)
    {
        if(s1%i == 0)
        {
            return false;
        }
    }

    return true;
}

Exercise 6


static int[] OddNumbers(int[] arr)
{
            
    int[] odds = new int[arr.Length];
    for (int i = 0; i < arr.Length; i++)
    {
        if (arr[i]%2 == 1 )
        {
            tekler[i] = arr[i];
        }
                
    }
            
    return odds;
}

Exercise 7

static List<int> SqrList(List<int> l)
{
    List<int> list = new List<int>();
    foreach (var item in l)
    {
        list.Add(item * item);
    }
    return list;
}

Params

params is a keyword that allows methods to accept a variable number of arguments. You can see how to use it by looking exemples below.
This method takes numbers and returns the sum of these numbers. You are not restricted to enter a certain number of parameters. Using params lets you to decrase numbers of overloading methods.

static int Sum(params int[] numbers)
{
    int result = 0;
    foreach (var num in numbers)
    {
        result += num;
    }
    return result;
}

Exercise 8

Returns user's name and the sum of user's scores after getting name and scores from user.

static string PuanTopla(string isim, params int[] scores)
{
    int result = 0;
    foreach (var score in scores)
    {
        result += score;
    }
    return isim +" "+ + "Total score : "+result;
}

Recursive Functions

Recursive function is a function that calls itself.

Exercice 9

Write the method that calculates the factorial of a number. When we call factorialCalculator() method and try to learn 5!. this method will reach the result by following the steps below:
factorialCalculator(5) => 5*factorialCalculator(4) => 5*4* factorialCalculator(3) => 5*4*3* factorialCalculator(2) => 5*4*3*2*factorialCalculator(1) => 5*4*3*2*1 = 120

static int factorialCalculator(int s1)
{
            
    if (s1 == 1)
    {
        return s1;
    }
    else
    {
        return s1 * faktorielCalculator(s1 - 1);
    }
}

Ref and Out

ref and out are keywords used to pass the data of value type to methods by reference. However, when we use ref, the initial value should be given to the variable, while using the out keyword, it is not necessary to give the initial value.

class MyFirstProgram
{
  static void Main(string[] args){

     // ref
     init number1 =0;
     HowtoRefWork( ref number1);// If no value is given, it will throw an error.

    
     // out
    init number2;// We declared without assigning value.
    HowtoOutWork(out number2)
  }

  static void HowtoOutWork(ref init number) 
  {
     number = 4242;
  }

  static void HowtoRefWork(out init number) 
  {
     number = 4242;
  }
}