Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any easier way of creating overload for methods in C#?

This is a general programming doubt rather than a specific one. But I would state it with an example. Suppose I'm creating a MessageBox class of mine own, and I want .Show() method to be implemented with say 21 overloads. I can do this like shown below.

public static void Show(string x){}
public static void Show(int x){}
public static void Show(param x){}
public static void Show(param2 x){}
public static void Show(string x, param y){}
.
.
.
.
public static void Show(param x, param y){}

Writing 21 such methods becomes quite a hassle. Is there any simpler way to do this? Something like,

public static void Show(string x, string y, int i, param p, ...... param21st z)
{
    if (//see the arguments and decide)
        //do stuff ignoring rest of the arguments;
    else if (//passed arguments are of these type)
        //then do this stuff.
    else if (so and so)
        // so and so.
}

Note: 1. I know there can be arguments like wouldn't it make my single function so big that it can exceed the size of separately written 21 different functions. No. In my case writing separately is a bigger hassle considering what I need to execute under the function is very trivial (only that the function may take a large number of parameters). Moreover this question is also to know about different coding techniques. 2. I understand the concise style i'm searching for has its demerits, in my case, its for a hobby program I'm creating for myself. So doesnt matter the usability. Just that i need to execute .Show() method with every combination of parameters possible to pass. (That makes writing separate functions so tedious).

Thanks.

like image 254
nawfal Avatar asked Jan 19 '23 06:01

nawfal


1 Answers

You could do this, but you would have to know the type of parameters in the function.

public static void Show(params object[] values)
{
   if(values[0] == "something")
   //Do stuff
}
like image 131
Magnus Avatar answered Mar 15 '23 11:03

Magnus