In C#, methods are blocks of code that perform a specific task and can be called upon when needed. They help in organizing code into manageable sections, making it easier to read, maintain, and reuse. A method is defined with a specific name, and it can accept parameters and return a value.
Structure of a Method
A method typically includes the following components:
Access Modifier: Determines the visibility of the method (e.g., public, private).
Return Type: Specifies the type of value the method returns. If it doesn’t return a value, use void.
Method Name: A descriptive name that identifies the method.
Parameters: A comma-separated list of inputs the method accepts, enclosed in parentheses (). Parameters are optional.
Method Body: The block of code enclosed in curly braces {} that defines what the method does.
Here’s the syntax for defining a method in C#:
publicreturnTypeMethodName(parameterTypeparameterName) { // Code to be executed }
Example
usingSystem;
classProgram { // Method to add two integers publicstaticintAddNumbers(intnum1, intnum2) { intsum=num1+num2; returnsum; }
staticvoidMain() { // Calling the AddNumbers method and storing the result intresult=AddNumbers(4, 5);
// Printing the result Console.WriteLine("The sum is: "+result); //output- The sum is: 9 } }
Explanation of the Example
Method Definition: We define a method called AddNumbers that:
Is public, meaning it can be accessed from outside the class.
Is static, meaning it belongs to the class itself rather than an instance of the class.
Has a return type of int, indicating it returns an integer value.
Takes two parameters: int num1 and int num2.
Method Body:
The method calculates the sum of num1 and num2 and stores the result in the variable sum.
It then returns the value of sum.
Main Method:
The Main method is the entry point of the program.
It calls the AddNumbers method with arguments 4 and 5, and stores the returned value in the result variable.
Finally, it prints the result to the console.
Benefits of Using Methods
Code Reusability: Methods allow you to write code once and reuse it multiple times, reducing redundancy.
Modularity: Breaking down complex tasks into smaller methods makes the code more modular and easier to manage.
Readability: Descriptive method names and clear structure improve the readability of the code.
Maintenance: Changes can be made in one place (the method) rather than in multiple locations where the code might be repeated.