With the help of this method, we can manage our code in a proper way. Sometimes, we need to write some set of code more than one time in our program and it increases the size of a program and is not easy to manage the code to solve these problems. We used the method given below:
Syntax of declaring the method is given bellow,
- returnType methodeName (parameterList)
- {
- //method body
- }
methodName is used to call the method. We should follow camelCase convention for the method name.
parameterList is an option. We provide parameterList or not, according to our need
Example
- void myFirstMethod()
- {
- // Do somthings
- }
- void mySecondMethod(int i)
- {
- }
How to return data from Method
If we want to return data from the method, first, define the return type of the method but it is not a void type. When we use void, it means the method should not return any data. We used the return keyword to achieve this target.
Example
- int addTwoValue (int first, int second)
- {
- return first + second;
- }
If you want the method, not return data, you should use void keyword.
- void displayInfo( int dataDisplay)
- {
- Console.WriteLine(dataDisplay);
- }
This is best the feature of C#. C# uses the position of each parameter to determine which parameter is passed. We can change the position of the parameters, when we call the method.
Example
- void myMethod(int first, int second=10,string third=”hi”)
- {
- // do somthing
- }
- myMethod(1,20,”C#”);
- myMethod(first:10,second:10,third:”Name”);
- myMethod(second:20,first:10,third:”C#”);
- myMethod(1,second:60,”C#”);
There is some possibility of ambiguity, when we used optional parameter and the name argument. How does compiler understand this ambiguity?
Let’s see an example,
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Method
- {
- class Program
- {
- static void Main(string[] args) {
- myMethod(1, 0.0, "gg");
- myMethod(1, fourth: 300);
- Console.ReadKey();
- }
- public static void myMethod(int first, double second = 0.0, string third = "Hi") {
- Console.WriteLine("hi i am first");
- }
- public static void myMethod(int first, double second = 0.0, string third = "Hi", int fourth = 100) {
- Console.WriteLine("hi i am Scond");
- }
- }
- }
- void myMethod(int first, int second = 0, string third = ”Method”) {
- // Do something
- }
- void myMethod(int first, int second = 0, string third = ”Method”, int forth = 1) {
- //Do something
- }
myMethod (1,2,”Hello”);
Do you know which method is called? Don’t worry, i's called first method, which has three parameters because the compiler checks closely match the method.
myMethod (1,forth:6);
Now, this is called a second method, which has a fourth argument.

Ritesh SinghPosted Aug 1, 2016, 10:17 AM
Nice