Methods & Functions
Learn to create and use methods to organize and reuse code effectively. This is a foundational concept in Microsoft application framework that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world .NET experience. Take your time with each section and practice the examples
What are Methods?
Methods are blocks of code that perform specific tasks. They help organize code, make it reusable, and improve readability. In C#, methods are defined within classes.. This is an essential concept that every .NET developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
Method Syntax
// Method declaration syntax
[access_modifier] [static] return_type MethodName(parameters)
{
// method body
return value; // if return_type is not void
}
// Example method
public static int Add(int a, int b)
{
int result = a + b;
return result;
}
// Method with no return value
public static void PrintMessage(string message)
{
Console.WriteLine(message);
}
// Method with no parameters
public static void SayHello()
{
Console.WriteLine("Hello, World!");
}Method Parameters
// Value parameters
public static int Multiply(int x, int y)
{
return x * y;
}
// Reference parameters (ref)
public static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
// Output parameters (out)
public static void Divide(int a, int b, out int quotient, out int remainder)
{
quotient = a / b;
remainder = a % b;
}
// Params array
public static int Sum(params int[] numbers)
{
int total = 0;
foreach (int num in numbers)
{
total += num;
}
return total;
}
// Optional parameters with default values
public static void Greet(string name, string greeting = "Hello")
{
Console.WriteLine($"{greeting}, {name}!");
}Method Overloading
// Method overloading - same name, different parameters
public static int Add(int a, int b)
{
return a + b;
}
public static double Add(double a, double b)
{
return a + b;
}
public static int Add(int a, int b, int c)
{
return a + b + c;
}
// Usage
int sum1 = Add(5, 10); // Calls first method
double sum2 = Add(5.5, 10.5); // Calls second method
int sum3 = Add(5, 10, 15); // Calls third methodRecursive Methods
// Recursive method - calls itself
public static int Factorial(int n)
{
if (n <= 1)
return 1;
else
return n * Factorial(n - 1);
}
// Fibonacci sequence
public static int Fibonacci(int n)
{
if (n <= 1)
return n;
else
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
// Usage
int fact = Factorial(5); // 120
int fib = Fibonacci(10); // 55