A method in C# is a block of code that performs a particular task. Methods help you reuse code, keep it organized, and make it easier to read and maintain.
returnType MethodName(parameters)
{
// code to execute
}
using System;
class Program
{
static void Greet()
{
Console.WriteLine("Hello, welcome to C#!");
}
static void Main()
{
Greet(); // Call the method
}
}
static void PrintMessage(string name)
{
Console.WriteLine("Hello " + name);
}
static void Main()
{
PrintMessage("Technorank");
}
static int Add(int a, int b)
{
return a + b;
}
static void Main()
{
int result = Add(5, 7);
Console.WriteLine(result); // Output: 12
}
You can define multiple methods with the same name but different parameters.
static int Multiply(int a, int b)
{
return a * b;
}
static double Multiply(double a, double b)
{
return a * b;
}
static void Main()
{
Console.WriteLine(Multiply(4, 3)); // 12
Console.WriteLine(Multiply(2.5, 4.2)); // 10.5
}
static
(used without creating an object) or instance-level (called via objects).
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!