C# Methods and Parameter Passing

Complex applications have huge code base with more than thousands line of code. Writing them in one method is certainly not a good idea. Therefore, we split our code into manageable pieces or units. One way to manage code is by defining methods that perform unified tasks.

cheezycode-csharp-methods-parameters-pass

What is a Method?


Method is a set of statements or operations. This is just a code block with more than one statement. In well written form of code, methods perform only one task. It is a 2-Step process to use methods - first you need to define it and second you need to call that method to achieve the desired functionality. Now, whenever you need that functionality, just call that method. You define a method like this -

access-modifier returnType methodName(multiple parameters)
{
  .... body of the method ....

  return result;
}

access-modifier is optional so we can just ignore this for a moment and focus on how to define a method and call it. We will cover access modifier in future posts. returnType defines the data type of the output of this method. methodName is a valid name that you want to give to your functionality. parameters- these are the inputs you want to provide to this method to execute the functionality. body of the method is the code you want to execute. return is the last statement in the method which returns the result. Data type of the result and return type must match. Once you define the method, you call it like this - methodName(input Parameters);

Let's take one example to make it more clear - You want to add 2 numbers and display its total -

static void Add()
{
    int a = 12;
    int b = 13;
    int total = a + b;
    Console.WriteLine(total);
}

We have defined a method - Add. This method defines 2 integer variables a and b, calculates its total by adding them and prints that total onto the screen. It does not return any value- to indicate this we have used void keyword as a return type. Void is a restricted word or keyword in C# that has a special meaning. Static Keyword will be covered later. Now, whenever we want to calculate the sum of 12 and 13, we will call this method as shown below. (calling is done in Main method)

using System;
class Program
{
    static void Main(string[] args)
    {
        Add(); // This line calls Add() Method     
        Console.ReadKey();
    }

    static void Add()
    {
        int a = 12;
        int b = 13;
        int total = a + b;
        Console.WriteLine(total);
    }
}

Parameter Passing 


Though the above code snippet, separates out the addition of numbers but it just add only 12 and 13. We want a method which is generalised i.e. we provide the numbers as input to the method - for this we will use input parameters.

using System;
class Program
{
    static void Main(string[] args)
    {
        Add(12, 13); //Here we pass 12 and 13 as input
        Add(5, 10); // Now Add Method is generalised, we pass different input    
        Console.ReadKey();
    }

    static void Add(int a, int b)
    {        
        int total = a + b;
        Console.WriteLine(total);
    }
}

This method takes 2 numbers as input parameters, adds and prints the sum of both. We want this method to return the result instead of printing the output on the screen. Why? As mentioned above, it is best to separate the functionality - each method should have only task. In this case, we want Add method to perform only addition and return the result. We leave the rest to the caller of this method. To make it more clear - If we allow Add method to print the result as well and at some place we want to add two numbers again without printing them, we cannot use this Add method because it prints the output as well. So to reuse the same code again we exclude printing of the result.

ONE METHOD SHOULD PERFORM ONLY ONE TASK

Improved version of Add Method

using System;
class Program
{
    static void Main(string[] args)
    {
        int total = Add(5, 6); // Now Add method returns the result. 
        Console.WriteLine(total);

        // We can reuse the method again as it perform only addition
        total = Add(total, 2);
        
        Console.ReadKey();
    }

    static int Add(int a, int b)
    {        
        int total = a + b;
        return total;

        //or you can directly return the result as 
        // return a + b;       
    }
}

Program flow when you call a method


cheezycode-method-execution-flow


When you call a method, execution jumps to the first line of the method and starts from that line. Once it reaches the end of the method (either return keyword or curly brace "}" ), execution jumps to the caller of the method and starts execution from the very next statement of method call. Refer above image for the illustration of how execution is done.

This covers the basics of C# methods and parameter passing. We will learn more about this in future posts. Let us know your thoughts on this. Happy Reading 






Comments

Popular posts from this blog

Create Android Apps - Getting Started

Kotlin Type Checking and Smart Cast with Examples