C# Methods

Basic overview of the C# methods.

C# Methods

Methods are code blocks that contain a series of statements. They are used to perform a specific task or set of tasks. Methods are an essential part of the object-oriented programming paradigm in C#. Here's a basic overview of C# methods:

Syntax:

access_modifier return_type MethodName(parameter_list)
{
    // method body
    // statements
    // return statement (if applicable)
}

Access Modifier: Specifies the visibility of the method (e.g., 'public', 'private', 'protected', etc.).

Return Type: Specifies the type of value that the method returns. If the method doesn't return a value, use 'void'.

Method Name: The name of the method, following the C# naming conventions.

Parameter List: A list of input parameters that the method accepts. Parameters are optional.

Method Body: Contains the statements that define the functionality of the method.

Return Statement: If the method has a return type other than 'void', it must include a return statement to 'return' a value.

Example:

cs Copy Code
using System;

class Program
{
    static void Main()
    {
        // Calling the method
        int sum = AddNumbers(5, 10);
        Console.WriteLine("Sum: " + sum);
    }

    // Method definition
    static int AddNumbers(int a, int b)
    {
        int result = a + b;
        return result; // Return statement
    }
}
Output:
Sum: 15

In this example, 'AddNumbers' is a method that takes two integers as parameters, adds them, and returns the result. The 'Main' method demonstrates how to call this method and use its result.

Types of Methods

1. Static Methods: Belong to the class rather than an instance of the class. They are called using the class name.

class MyClass
{
    public static void StaticMethod()
    {
        // Method body
    }
}                                

2. Instance Methods: Belong to an instance of the class and can access instance-level members.

class MyClass
{
    public void InstanceMethod()
    {
        // Method body
    }
}

3. Parameterless Methods: Methods that don't take any parameters.

class MyClass
{
    public void ParameterlessMethod()
    {
        // Method body
    }
}

4. Methods with Parameters: Methods that take one or more parameters.

class MyClass
{
    public void MethodWithParameters(int param1, string param2)
    {
        // Method body
    }
}

* These are just basic examples, and C# supports many other features related to methods, such as method overloading, optional parameters, and more.

What is New?

We have just updated this website & still working on adding new content & updating existing features.