Method Definitions and Usage in C#
A method is a named block of code that encapsulates a set of instructions to perform a specific task. Programs are structured using methods to promote code reuse and organization. Every C# application contains at least one class with a Main method, which serves as the entry point.
To utilize a method, it must first be defined and then invoked.
Syntax
[access-modifier] [static] return-type MethodIdentifier([parameter-list])
{
// Method body
}
- Access Modifier: Controls visibility (e.g.,
public,private). - Static: Indicates the method belongs to the type itself, not an instance.
- Return Type: The data type of the value returned. Use
voidif no value is returnde. - Method Identifier: The name of the method, following PascalCase convention.
- Parameter List: Comma-separated list of input values reequired by the method.
Invocation of a static method is done via ClassName.MethodIdentifier(). If the call is within the same class, the class name can be omitted.
Basic Example: Finding Maximum Value
public static int FindMaximum(int firstValue, int secondValue)
{
return firstValue > secondValue ? firstValue : secondValue;
}
// Usage
int maximum = FindMaximum(10, 25);
Console.WriteLine(maximum); // Output: 25
Parameter Types
Out Parameters
An out parameter allows a method to return multiple values. The method must assign a value to the out parameter before exiting.
Example: Parsing a string to an integer.
public static bool TryParseInteger(string input, out int result)
{
if (int.TryParse(input, out result))
{
return true;
}
result = -1; // Default value on failure
return false;
}
// Usage
if (TryParseInteger("123", out int parsedValue))
{
Console.WriteLine($"Parsed value: {parsedValue}");
}
Ref Praameters
A ref parameter passes an argument by reference, allowing the method to modify the original varialbe.
Example: Adjusting a temperature value.
public static void ApplyOffset(ref double temperature, double offset)
{
temperature += offset;
}
// Usage
double currentTemp = 22.5;
ApplyOffset(ref currentTemp, 1.5);
Console.WriteLine(currentTemp); // Output: 24.0
Params Keyword
The params keyword enables a method to accept a variable number of arguments of the same type. It must be the last parameter in the list.
Example: Calculating the average of grades.
public static double CalculateAverage(params double[] grades)
{
if (grades.Length == 0) return 0;
double total = 0;
foreach (var grade in grades)
{
total += grade;
}
return total / grades.Length;
}
// Usage
double avg1 = CalculateAverage(85.5, 90.0, 78.5);
double avg2 = CalculateAverage(92.0, 88.5, 95.5, 89.0);
Method Overloading
Method overloading allows multiple methods in the same scope to have the same name but different parameters. Differences can be in the number of parameters or their types. Return type alone is not sufficient for overloading.
public static int Compute(int a, int b) => a + b;
public static double Compute(double a, double b) => a * b;
public static int Compute(int a, int b, int c) => a + b + c;
Recursion
Recursion occurs when a method calls itself. It requires a base case to terminate the calls.
Example: Computing the factorial of a number.
public static int Factorial(int n)
{
if (n <= 1) // Base case
return 1;
return n * Factorial(n - 1); // Recursive call
}
// Usage
int fact = Factorial(5); // Returns 120