C# Methods

In C#, methods are used to define a block of code or statements, which we can use again and again, to simply the code readability and usablity. A method consist of one or more coding statements, which we can execute by calling methods name.

Syntax to create methods or functions in C#

<Access specifier> <Return Type> <Method Name> (Parameter List)
{
  //  Method Body
  //code statements
}

Where,

Access Specifier = Private, Public, Protected etc, determines if method can be accessed from different class ( if public) or not (if private).
                                          It is optional. If you don't define any, then the function will be private. by default.

Return type= return type can be of any datatype like int, string, any class, char, list etc.
                              return type= void, when method doesn't return anything.

Method Name= it can be anything, should be a useful name.

Parameter List = list of variables which we will pass to method and will be used inside it.

Example:

using System;
					
public class Program
{
	public static void Main()
	{
		//call method	
		AddTwoNumber(a,b);
	}
	public static void AddTwoNumber()
	{
               int a=10, b=20;
		 int c= a+b;
		 Console.WriteLine("Sum ="+c);  
	}
}

Note: In C#, methods and functions are same things, these are two names of doing same thing in C#

Above example shows a simple method, which adds two numbers ( a+ b) and print the value (c).

In the above method, we have used static keyword, using static keyoword means we don't need to create it's class (Program in this example) instance and call it.

If you don't want to use it as static keyword, you need to create instance ( object ) of it's class and call it.

Note: If you are not familier with Class and objects, we will discuss it in later chapter in detail or you can read the article Object Oriented Programming (OOPS) concepts in c# with example

using System;
					
public class Program
{
	public static void Main()
	{		
		//create class instance
		Program p= new Program();
		//call method using class instance created above
		p.AddTwoNumber();
	}
	//void is return type, means it will not return anything
	//public is acces type, means it can be accessed from anywhere in the program
	public void AddTwoNumber()
	{
		 int a=10, b=20;
		 int c= a+b;
		 Console.WriteLine("Sum ="+c);  
	}
}

Static methods in C#

Static methods are the methods, which don't require class object to call them, we can directly invoke them without creating object.

As you can see in the last example, we created Program class object (Program p = new Program()) and called the method using that object (p), but in-case of static methods, we can call the method directly from another static method, without creating it's object.

Example:

using System;

//this is class
public class Program
{
	//this is main method, which is also static
	public static void Main()
	{
		//static method
		AddTwoNumber();
	}
	//we have used static keyword, so we don't need to class it's class object
	public static void AddTwoNumber()
	{		
		 int a=10, b=20;		
		 int c= a+b;
		 Console.WriteLine("Sum ="+c);  
	}
}

Above program lines has been explained more using comments.

Methods with parameters in C#

We can pass some datatype to methods in C#, which will be used inside the methods code. The list of parameters can be added in the parentheses followed by the method name. Each parameter has a name and a type. The syntax of parameter is similar to the declaration of the local variables.

Example of method with paramters

public void MethodWithParameters(int x, string y)
{
 //some code
}

As you can see in the above example, we are passing parameters int x and string y, to the method.

Parameters can be passed using the three mechanisms:

  1. Value: They are referred as ‘Input Parameters’ as the data can be passed to the method but it cannot be returned. The changes added to the method cannot be reflected outside the method.
  2. Reference: They are referred as Input/Output parameters as the data can be passed to the method and returned by it. The changes made to the method are reflected outside the method.
  3. Output: They are refereed as Output parameters as the data can be extracted from the method. Any changes made to the method are reflected outside the method. They are declared by using out keyword specified before the parameter type and name.

Passing Parameter by value

Passing parameters by value is the default type for passing parameters to the method. The value parameter is defined by specifying the data type followed by the variable name.

The values in the variable are passed when the method is invoked, here is the simple example

using System;
					
public class Program
{
	//method is returning int value
	public int AddOne(int i)
    {
        i=i + 1;
		return i;
    }
    public static void Main( )
    {
		//creat program class object, p
        Program d = new Program();
        int no = 5;
		//call method using p object and passing parameter, get update value
        no=d.AddOne(no);		
        Console.WriteLine("The new number is:" +no);
      
    }
}

In the above method AddOne(int i) , we are passing value of no as 5 and getting it's value as 6, so return type= int.

Passing parameters as reference

Instead of passing value, we will be passing reference, that is, memory location of the variable.

In reference parameter new storage location is not created. It stores the value in the same memory location as the variable passed in the memory call.

The declaration of the reference parameter is done by using the ref keyword. The example for the reference parameters is as shown below:

void MethodByReference( ref int id, ref int age )
{
 
}

Take a look at an example

using System;
					
public class Program
{
	public static void Main(string[] args)
	{
		int number = 20;
		//no need to return a value, as reference is updated
		AddFive(ref number);
		Console.WriteLine(number);		
	}
    //reference is passed to this method
	public static void AddFive(ref int number)
	{
		number = number + 5;
	}
}

As you can see, we've added the ref keyword to the function declaration as well as to the call function. If you run the program now, you will see that the value of number has now changed, once we return from the function call.

Passing parameter as out

A return statement is used for returning a value from the method. A return statement can be used to return only a single value. The output parameter is used to overcome this problem. The out modifier works pretty much like the ref modifier.

A value passed to a ref modifier has to be initialized before calling the method - this is not true for the out modifier, where you can use un-initialized values. On the other hand, you can't leave a function call with an out parameter, without assigning a value to it.

Example:

using System;
					
public class Program
{
	public static void OutSample( out int i )
    {
        i=20;
    }
    public static void Main()
    {
        int no;
        OutSample( out no );
        Console.WriteLine("Value for the number is: " +no );
       
    }
}


Share Tweet