
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Arithmetic Operators
- C# - Assignment Operators
- C# - Relational Operators
- C# - Logical Operators
- C# - Bitwise Operators
- C# - Miscellaneous Operators
- C# - Operators Precedence
- C# Conditional Statements
- C# - Decision Making
- C# - If
- C# - If Else
- C# - Nested If
- C# - Switch
- C# - Nested Switch
- C# Control Statements
- C# - Loops
- C# - For Loop
- C# - While Loop
- C# - Do While Loop
- C# - Nested Loops
- C# - Break
- C# - Continue
- C# OOP & Data Handling
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
C# - Methods
A method is a block of code that contains a group of statements that together perform a task. Every C# program has at least one class with a method named Main.
To use a method, you need to −
- Define the method
- Call the method
Defining Methods in C#
When you define a method, you basically declare the elements of its structure. The syntax for defining a method in C# is as follows −
Syntax
<Access Specifier> <Return Type> <Method Name>(Parameter List) { Method Body }
Elements of a C# Method
Following are the various elements of a method −
Access Specifier − This determines the visibility of a variable or a method from another class.
Return type − A method may return a value. The return type is the data type of the value the method returns. If the method is not returning any values, then the return type is void.
Method name − Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class.
Parameter list − Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.
Method body − This contains the set of instructions needed to complete the required activity.
Example to Define a Method
Following code snippet shows a function FindMax that takes two integer values and returns the larger of the two. It has public access specifier, so it can be accessed from outside the class using an instance of the class.
class NumberManipulator { public int FindMax(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; } ... ... }
Calling Methods in C#
You can call a method by using its name along with parentheses (). If the method belongs to an object, you call it using the object name followed by a dot (.). If it's a static method, you call it using the class name.
Example 1
In the following example, we create a class that contains a method FindMax that takes two integer parameters, compares them, and returns the larger of the two −
using System; namespace CalculatorApplication { class NumberManipulator { public int FindMax(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; } static void Main(string[] args) { /* local variable definition */ int a = 100; int b = 200; int ret; NumberManipulator n = new NumberManipulator(); //calling the FindMax method ret = n.FindMax(a, b); Console.WriteLine("Max value is : {0}", ret ); Console.ReadLine(); } } }
Output
When the above code is compiled and executed, it produces the following result −
Max value is : 200
Calling Method from Another Class
You can also call public method from other classes by using the instance of the class. For example, the method FindMax belongs to the NumberManipulator class, you can call it from another class Test.
Example
Here in this example, we find the maximum of two numbers using a method in C# and demonstrate the process of calling a method from another class −
using System; namespace CalculatorApplication { class NumberManipulator { public int FindMax(int num1, int num2) { /* local variable declaration */ int result; if(num1 > num2) result = num1; else result = num2; return result; } } class Test { static void Main(string[] args) { /* local variable definition */ int a = 100; int b = 200; int ret; NumberManipulator n = new NumberManipulator(); //calling the FindMax method ret = n.FindMax(a, b); Console.WriteLine("Max value is : {0}", ret ); Console.ReadLine(); } } }
Output
When the above code is compiled and executed, it produces the following result −
Max value is : 200
Recursive Method Call
A method can call itself. This is known as recursion. Following is an example that calculates factorial for a given number using a recursive function −
Example
using System; namespace CalculatorApplication { class NumberManipulator { public int factorial(int num) { /* local variable declaration */ int result; if (num == 1) { return 1; } else { result = factorial(num - 1) * num; return result; } } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); //calling the factorial method {0}", n.factorial(6)); Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7)); Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8)); Console.ReadLine(); } } }
Output
When the above code is compiled and executed, it produces the following result −
Factorial of 6 is: 720 Factorial of 7 is: 5040 Factorial of 8 is: 40320
Types of Methods in C#
Based on the functionalities, C# methods can be divided into the following types:
- Simple Method Without Parameters
- Method With Parameters
- Method With Return Value
- Method Overloading (Same Method, Different Parameters)
- Method with Default Parameters
1. Simple Method Without Parameters
This type of method does not take any arguments and can be defined when there is no need for external input during the function call.
In the following example, we are defining a method without parameters and calling it directly:
using System; class Program { static void WelcomeMsg() { Console.WriteLine("Hello, Welcome to C# Tutorial!"); } static void Main() { WelcomeMsg(); // Calling the method } }
When the above code is compiled and executed, it produces the following result −
Hello, Welcome to C# Tutorial!
2. Method With Parameters
When you have external (to the function) input, i.e., you want to pass values during the function call, you can define this type of method; it allows you to pass values that can be used within the method.
In the following example, we are defining a method that accepts parameters to perform dynamic operations:
using System; class Program { static void Add(int a, int b) { Console.WriteLine("Sum: " + (a + b)); } static void Main() { Add(5, 10); Add(20, 30); } }
When the above code is compiled and executed, it produces the following result −
Sum: 15 Sum: 50
3. Method With Return Value
This type of method is useful when a method performs some operation and you want the result in the caller method. The value is returned from the method using the return statement. Further, you can use and store the returned value.
In the following example, we are defining a method that returns a value using the return statement:
using System; class Program { static int Multiply(int x, int y) { return x * y; // Returns the product } static void Main() { int result = Multiply(4, 5); Console.WriteLine("Multiplication Result: " + result); } }
When the above code is compiled and executed, it produces the following result −
Multiplication Result: 20
4. Method with Default Parameters
You can also define a method by providing the default values. If no argument is passed while calling the method, the default value is used.
In the following example, we are defining a method with default parameter values:
using System; class Program { static void WelcomeMsg(string name = "Guest") { Console.WriteLine("Hello, " + name); } static void Main() { WelcomeMsg(); // Uses default value WelcomeMsg("Krishna K."); // Uses provided value } }
When the above code is compiled and executed, it produces the following result −
Hello, Guest Hello, Krishna K.
Passing Parameters to a Method
When method with parameters is called, you need to pass the parameters to the method. There are three ways that parameters can be passed to a method −
Sr.No. | Mechanism & Description |
---|---|
1 |
Value parameters
This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. |
2 |
Reference parameters
This method copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument. |
3 |
Output parameters
This method helps in returning more than one value. |