Methods: Method Declaration and Definition in C#
Introduction
In C#, methods are blocks of code that perform a particular task. They are essential building blocks of any C# program. Understanding how to declare and define methods is crucial for any C# programmer. This tutorial will guide you through the process of method declaration and definition, explaining each part with examples.
Method Declaration
Method declaration in C# involves specifying the method's signature, which includes the access modifier, return type, method name, and parameters. Here's the syntax for declaring a method:
For example, let's declare a simple method that adds two integers:
In this example:
- public is the access modifier.
- int is the return type.
- Add is the method name.
- int a, int b are the parameters.
Method Definition
Method definition includes the actual implementation of the method. It involves writing the block of code that performs the specific task. The syntax for defining a method is:
// method body
}
Let's define the Add method we declared earlier:
return a + b;
}
Complete Example
Here is a complete example of a C# program that declares and defines multiple methods:
namespace MethodExample {
class Program {
static void Main(string[] args) {
Program p = new Program();
int sum = p.Add(5, 3);
Console.WriteLine("Sum: " + sum);
}
public int Add(int a, int b) {
return a + b;
}
}
}
In this example:
- Main method is the entry point of the program.
- The Add method is defined within the Program class.
- An instance of the Program class is created to call the Add method.
- The result of the Add method is printed to the console.
Method Overloading
Method overloading allows you to define multiple methods with the same name but different parameter lists. This adds flexibility to your code. Here's an example of overloaded methods:
return a + b;
}
public double Add(double a, double b) {
return a + b;
}
In this example, we have two Add methods: one that takes integers and another that takes doubles.
Conclusion
Understanding method declaration and definition is fundamental in C# programming. Methods allow you to encapsulate code and make it reusable and more manageable. This tutorial has covered the basic syntax and concepts, including method overloading. Practice writing your methods to get a solid grasp of these concepts.