Method Groups in C#

  1. Method Group in C#
  2. Delegates in C#
  3. Method Groups Conversion With DELEGATE in C#
  4. Simple Custom Delegate for Method Groups in C#
  5. Use Function Pointers for Method Groups in C#
Method Groups in C#

This article will tackle method groups in C#.

Method Group in C#

We sometimes encounter a case where a function may have more than one implementation. It might have another definition with an entirely different parameter set or type or is usually known as an overloaded function.

Syntax:

void print(int x){
///...code
}

void print(int x, int y){
///...code for x and y
}

Such functions or methods are called METHOD GROUPS.

Delegates in C#

DELEGATES are pointers to functions created. Along with pointing to the function, it also defines the return type of the functions and their parameters.

A delegate, let’s say, called LAPTOP can have a return type as void and a parameter as USERNAME (string). We have another function called PC, which also has the same return type and parameter type as LAPTOP.

We can call PC from the delegate LAPTOP in this scenario.

Code Example:

        delegate void LAPTOP(string username);

        static void PC(string username)
        {
            Console.WriteLine("USER: " + username + " has logged in!");
        }

        static void Main()
        {
            LAPTOP lap1 = PC;
            lap1("Hydrogen");
        }

You can notice that we have instantiated the LAPTOP instance with PC, and invoking it later, causes us to print the username passed from the PC method. That is how DELEGATES work.

Method Groups Conversion With DELEGATE in C#

We’ll look at one of the most common uses of method groups and how to handle them when called. We discussed how method groups are overloaded functions of a basic method, and we can use method groups as we desire by using DELEGATES.

In our example, let’s suppose that we have a method called CAR from which we want to address several other methods, such as DASHBOARD, WHEEL, LIGHTS etc. We will, for convenience, only use two methods; LIGHTS and MIRRORS.

Code Example:

delegate void CAR(bool start);

        static void MIRROR(bool start)
        {
            if(start)
                Console.WriteLine("Mirror is now working!");
            else
                Console.WriteLine("Mirror is not stopped/closed");
        }

        static void LIGHTS(bool start)
        {
            if (start)
                Console.WriteLine("Lights are now working!");
            else
                Console.WriteLine("Lights have stopped/closed");
        }

Now that we have defined the methods let’s implement the MAIN method, where we use delegates to handle these method groups.

CAR car = MIRROR;
            car(true);

            car = LIGHTS;
            car(false);

You can notice the CAR object points to the MIRROR, but later it is made to point to LIGHTS. Then calling the method calls the function that it points to.

The function’s name is assigned to the car object. Changing the DELEGATE pointer to point at different methods in its group is called METHOD GROUP CONVERSION, and in this scenario, the LIGHTS, MIRRORS and CAR are all part of the same method group.

Simple Custom Delegate for Method Groups in C#

A simple way to create a DELEGATE that can point to METHOD GROUPS is something as simple as follows.

Func<string> f_test = "AA".ToString;
Console.WriteLine(f_test());

Invoking the above will output the string AA as a result. F_TEST points to the ToString method and calls it.

You can also notice that this function points to the address of the ToString method and not the function itself. That is how pointers work.

Another example has been provided below to understand METHOD GROUPS properly.

Func<string, int> f_test = Convert.ToInt32;
Console.WriteLine(f_test("435"));

Syntax:

Func<param1, param2> name;
//param1 is the parameter passed in the function/method pointed to
//param 2 is the return type of that function/method that the delegate points to

As Convert.ToInt32 has a return type of INT and 18 different overloads. It is imperative to define the parameter type because we want to call F_TEST with a string "435", and we define PARAM2 as STRING.

Defining PARAM2 is important even if there is just one overload of a function present; because METHOD GROUPS are compiled time constructs, they must be chosen for a single overload. It is important to ensure that PARAM2 contains at least one overload.

You can also remove the cast in LINQ when calling the List.Select(MethodGroup) in a function. We will not discuss LINQ contexts in detail because this article focuses on METHOD GROUPS.

Use Function Pointers for Method Groups in C#

Pointing to different functions from a delegate is only needed if you are working in METHOD GROUPS. You must ensure that the return types and parameters match in such circumstances.

C# already provides a FUNC keyword to allow for pointing to different functions. Just as pointers work by pointing to addresses of objects and variables and then calling them, you can imagine delegates the same way.

Pointers also tend to have the same return type as the objects they address. Delegates also have to take care of parameters due to function requirements.

Pointing to functions is needed when let’s say, you want to store functions in an array and call them dynamically for your code or pass the functions to other functions to be called. LAMBDA functions serve the same requirement as well.

However, METHOD GROUPS are common clusters with overloaded functions that follow a basic return and parameter type.

Author: Bilal Shahid
Bilal Shahid avatar Bilal Shahid avatar

Hello, I am Bilal, a research enthusiast who tends to break and make code from scratch. I dwell deep into the latest issues faced by the developer community and provide answers and different solutions. Apart from that, I am just another normal developer with a laptop, a mug of coffee, some biscuits and a thick spectacle!

GitHub

Related Article - Csharp Method

  • Optional Parameter in C#
  • Pass a Method as a Parameter in C# Function
  • Sort a List by a Property in the Object in C#
  • C# Pass Multiple Parameters to a Get Method
  • Override a Static Method in C#