C# Methods

Methods is simply a group of statements to perform a particular task in the program. Every C# program contains at least one method called Main() method.

Define a Method in C#

Here is the general form to define a method in C#:

access-specifier return-type method-name(parameter-list)
{
	statement(s);
}

Here is the explanation of the above method definition's general form:

  • access-specifier - determines the visibility of the method
  • return-type - data type of the value the method returns. In case if method doesn't return any value, then specify return-type as void
  • method-name - name of the method
  • parameter-list - the parameters are used to pass and receive data from the method.
  • statement(s) - this is the actual body of the method

Here, the following code fragment shows a function namely GetBigger that takes only two integer values (argument) and returns the larger of the two number.

class MethodExample
{
	public int GetBigger(int num1, int num2)
	{
		int res;
		if(num1>num2)
		{
			res=num1;
		}
		else
		{
			res=num2;
		}
		return res;
	}
	.
	.
	.
}

Calling a Method in C#

Here is an example program, demonstrating how to call a method in C#:

/* C# Methods - Example Program */
		
using System;
namespace NumberCalculator
{
	class MethodExample
	{
		public int GetBigger(int num1, int num2)
		{
			int res;
			if(num1>num2)
			{
				res=num1;
			}
			else
			{
				res=num2;
			}
			return res;
		}
		static void Main(string[] args)
		{
			int m=100;
			int n=300;
			int ret;
			MethodExample cal = new MethodExample();
			ret = cal.GetBigger(a, b);
			Console.WriteLine("Maximum Value = {0}", ret);
			Console.ReadLine();
		}
	}
}

When the above program is compile and run, it will produce the following output:

Maximum Value = 300

C# Online Test


« Previous Tutorial Next Tutorial »



Like/Share Us on Facebook 😋