Methods
A method is a block of code designed to perform a specific task. In C#, methods are
used to define functionality that can be invoked from other parts of the program.
Here's the general syntax for defining a method:
csharp
CopyEdit
access_modifier return_type MethodName(parameter_list) {
// method body
}
Parts of a Method:
• Access Modifier: Specifies the visibility of the method (e.g., public or private).
By default, methods are private if no access modifier is provided.
• Return Type: Specifies the type of value the method returns. If the method
doesn’t return a value, the return type is void.
• Method Name: The name of the method, which is case-sensitive. Method
names are followed by parentheses.
• Parameter List: Parameters are used to pass data to and from a method. They
are optional.
Here’s an example of two methods in C#:
Example 1: Void Method
csharp
CopyEdit
public void PrintRectangleArea(int width, int height) {
int area = width * height;
Console.WriteLine("The area of the rectangle is " + area);
}
Example 2: Method with Return Value
, csharp
CopyEdit
public int GetRectangleArea(int width, int height) {
int area = width * height;
return area;
}
To invoke a method, you call the method's name with the required arguments:
csharp
CopyEdit
DemoMethod obj = new DemoMethod(); // Creating an object instance
obj.PrintRectangleArea(5, 3); // Invoking the void method
int result = obj.GetRectangleArea(5, 3); // Invoking the method with return value
Console.WriteLine("Result = " + result);
Method Overloading
C# supports method overloading, allowing you to create methods with the same name
but different parameter types or numbers. The compiler selects the appropriate
method based on the arguments passed.
Example of Overloaded Methods:
csharp
CopyEdit
// Method for square area
public int GetArea(int side) {
return side * side;
}
// Method for rectangle area with integer parameters
public int GetArea(int width, int height) {