C# Methods

Methods in C# are blocks of code that perform specific tasks and can be called upon when needed. They help in organizing code, improving reusability, and making programs more modular and manageable.

Key Topics

1. Defining Methods

A method consists of an access modifier, return type, method name, and optional parameters enclosed in parentheses.

access_modifier return_type MethodName(parameter_list)
{
    // Method body
}

2. Calling Methods

Example: Creating and Calling a Method

class Program
{
    static void Main(string[] args)
    {
        Greet();  // Calling the method
    }

    static void Greet()
    {
        Console.WriteLine("Hello, World!");
    }
}

Output:

Hello, World!

3. Method Syntax

Understanding the components of a method declaration:

  • Access Modifier: Determines the visibility (e.g., public, private, static).
  • Return Type: Specifies the type of value the method returns (void if no value is returned).
  • Method Name: The identifier used to call the method.
  • Parameter List: Optional, defines input parameters.

Key Takeaways

  • Methods encapsulate code for reuse and organization.
  • They have a defined syntax including access modifiers and return types.
  • Methods can be called multiple times from different parts of the program.
  • Understanding method structure is essential for effective programming in C#.