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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With