Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to have conditional params arguments to a function

Tags:

c#

params

I have

public void Foo(string name, params object[] args)

I want to call it with a list of args that can vary. I need to do something like

Foo("yo",a,b,x==42?c);

ie if x is 42 then pass in a,b,c otherwise pass in a,b. Of course that syntax doesn't work. I know I could marshal the args to a List and pass the list to the function, but that would be very messy to do the way the code is organized. So is there some syntax magic i can use

EDIT: Let me add the concrete case

var xml = new XDocument(....,
   new XElement(....),
   new XElement(....),
   new XElement(....),
   x==42? new XElement(.....),
   new XElement(....),
   new XElement(....)
   ....
like image 618
pm100 Avatar asked May 21 '13 18:05

pm100


Video Answer


1 Answers

You can just use an if statement:

if (x == 42)
   Foo("yo", a, b, c);
else
   Foo("yo", a, b);

You can't use the ?: operator in this case (at least, outside of the function call), because Foo has no return value. The ?: operator must evaluate to something, and that something must be assigned to something else.

Another option that would get rid of the duplicate function call is to use an array or list for the params:

var parameters = new List<object> { a, b };

if (x == 42)
   parameters.Add(c);

Foo("yo", parameters);

And if you really wanted to get ?: in there, this would work, too:

Foo("yo", x == 42 ? new object[] { a, b, c } : new object[] { a, b });

For your more specific question about the XDocument/XElement constructor calls, you might want to use Add calls rather than one long series of constructor calls. Then you can make them conditional. As is, I think you should also be able to do what you're asking by doing something like 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 would look something like 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, one last version that is much closer to what you are asking for would be like this, which seems to work:

var xml = new XDocument(....,
   new XElement(...),
   new XElement(...),
   new XElement(...),
   x == 42
      ? new XElement(...)
      : null,
   new XElement(...),
   new XElement(...)
);
like image 93
Dave Cousineau Avatar answered Sep 28 '22 04:09

Dave Cousineau