c# - how to have conditional params arguments to a function -
i have
public void foo(string name, params object[] args)
i want call list of args can vary. need like
foo("yo",a,b,x==42?c);
ie if x 42 pass in a,b,c otherwise pass in a,b. of course syntax doesn't work. know marshal args list , pass list function, messy way code organized. there syntax magic can use
edit: let me add concrete case
var xml = new xdocument(...., new xelement(....), new xelement(....), new xelement(....), x==42? new xelement(.....), new xelement(....), new xelement(....) ....
you can use if statement:
if (x == 42) foo("yo", a, b, c); else foo("yo", a, b);
you can't use ?:
operator in case (at least, outside of function call), because foo
has no return value. ?:
operator must evaluate something, , must assigned else.
another option rid of duplicate function call use array or list params:
var parameters = new list<object> { a, b }; if (x == 42) parameters.add(c); foo("yo", parameters);
and if wanted ?:
in there, work, too:
foo("yo", x == 42 ? new object[] { a, b, c } : new object[] { a, b });
for more specific question xdocument
/xelement
constructor calls, might want use add
calls rather 1 long series of constructor calls. can make them conditional. is, think should able you're asking doing this:
xelement elementprecedingoptionalelement = new xelement(...); var xml = new xdocument(...., new xelement(...), new xelement(...), elementprecedingoptionalelement, new xelement(...), new xelement(...) ); if (x == 42) elementprecedingoptionalelement.addafterself(new xelement(...));
using add
calls this:
xdocument xml = new xdocument(); xelement root = new xelement("root"); xml.add(root); root.add(new xelement("item1")); root.add(new xelement("item2")); if (x == 42) root.add(new xelement("item2.5")); root.add(new xelement("item3")); root.add(new xelement("item4"));
actually, 1 last version closer asking this, seems work:
var xml = new xdocument(...., new xelement(...), new xelement(...), new xelement(...), x == 42 ? new xelement(...) : null, new xelement(...), new xelement(...) );
Comments
Post a Comment