Introduction to Methods in C#
What is a Method?
A method is a block of code that performs a specific task. It is a way to organize code into reusable units. Methods are used to perform actions, and they can take inputs and return outputs.
Defining a Method
In C#, a method is defined with the following syntax:
returnType MethodName(parameters)
{
// Method body
}
Here's a simple method example:
public int Add(int a, int b)
{
return a + b;
}
Calling a Method
To use a method, you need to call it. Here is how you call the Add method defined above:
int result = Add(5, 3);
Console.WriteLine(result); // Output: 8
Method Parameters
Methods can have parameters to accept inputs. Parameters are specified in the method definition within the parentheses.
Example:
public void Greet(string name)
{
Console.WriteLine("Hello, " + name);
}
Calling the method:
Greet("Alice"); // Output: Hello, Alice
Return Types
Methods can return a value. The return type is specified before the method name. Use void if the method does not return a value.
public int Multiply(int a, int b)
{
return a * b;
}
Calling the method and using the returned value:
int product = Multiply(4, 5);
Console.WriteLine(product); // Output: 20
Method Overloading
Method overloading allows you to define multiple methods with the same name but different signatures (different parameter types or number of parameters).
Example:
public void Print(int number)
{
Console.WriteLine("Number: " + number);
}
public void Print(string text)
{
Console.WriteLine("Text: " + text);
}
Calling the overloaded methods:
Print(10); // Output: Number: 10
Print("Hello"); // Output: Text: Hello
Static Methods
Static methods belong to the class itself rather than an instance of the class. They are called using the class name.
Example:
public class MathHelper
{
public static int Square(int number)
{
return number * number;
}
}
Calling the static method:
int squared = MathHelper.Square(4);
Console.WriteLine(squared); // Output: 16
Summary
In this tutorial, we covered the basics of methods in C#. We learned how to define and call methods, use parameters, return values, and implement method overloading. We also discussed static methods. Understanding methods is crucial for writing organized and reusable code.
