Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Method Definitions and Usage in C#

Tech 2

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 void if 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

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.