syntax - Is there any easier way of creating overload for methods in C#? -
syntax - Is there any easier way of creating overload for methods in C#? -
this general programming uncertainty rather specific one. state example. suppose i'm creating messagebox class of mine own, , want .show() method implemented 21 overloads. can 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 hassle. there simpler way this? like,
public static void show(string x, string y, int i, param p, ...... param21st z) { if (//see arguments , decide) //do stuff ignoring rest of arguments; else if (//passed arguments of these type) //then stuff. else if (so , so) // , so. } note: 1. know there can arguments wouldn't create single function big can exceed size of separately written 21 different functions. no. in case writing separately bigger hassle considering need execute under function trivial (only function may take big number of parameters). question know different coding techniques. 2. understand concise style i'm searching has demerits, in case, hobby programme i'm creating myself. doesnt matter usability. need execute .show() method every combination of parameters possible pass. (that makes writing separate functions tedious).
thanks.
the 2 options see are: 1. optional parameters, , 2. having methods phone call each other needed. both cut down amount of code need write.
here's illustration of optional parameters (vs 2010 or later). in string x = "", "" default x. defaults must compile-time constants.
public static void show(string x = "", string y = null, int = 0, param p = null, ...... param21st z = null) { if (//see arguments , decide) //do stuff ignoring rest of arguments; else if (//passed arguments of these type) //then stuff. else if (so , so) // , so. } when phone call it, if don't include parameters, might need name them it's obvious compiler , aren't specifying:
custommessagebox.show(x: "hi", y: "there", p: myobject); it's compiler trick automatically fills in non-included parameters defaults.
the other alternative have methods phone call each other possible. way you're not duplicating code 21 times, many major different ways can run.
public static void show(string x){show(x, null);} public static void show(int x){//do something} public static void show(param x){show(string.empty, x);} public static void show(param2 x){//do something} public static void show(string x, param y){//do something} an advantage of doing way can pass things besides constants, such new instantiations of objects or static readonly things.
c# syntax overloading argument-passing
Comments
Post a Comment