codescracker


c#

C# Methods



« Previous Tutorial Next Tutorial »


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:

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

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test