Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline conditional c# - next best solution?

Tags:

c#

casting

It seems the compiler is not going let this syntax fly.

void main()
{
  foo(false?0:"");
}

void foo(int i) {return;}
void foo(string s) {return;}

The only other way I can see of fixing this is something as follows:

void bar(object o) 
{
 if (o is string){//do this}
 else{//im an int, do this}
}

Anyone have any better ideas?

like image 333
maxp Avatar asked Dec 23 '22 00:12

maxp


2 Answers

You cannot use a method with a void return type in a ternary expression in this way. End of story.

To understand why this is, remember what the ternary operator actually does -- it evaluates to the following:

(condition ? [true value] : [false value])

What this implies is that the following code:

int x = a ? b : c;

Must be rewritable to:

int x;
if (a)
{
    x = b;
}
else
{
    x = c;
}

The two above are logically identical.

So how would this work with a method with void as its return type?

// Does this make sense?
int x = condition ? foo(s) : foo(i);

// Or this?
if (condition)
{
    x = foo(s);
}
else
{
    x = foo(i);
}

Clearly, the above is not legal.

That said, others' suggestions would otherwise be valid if only your foo overloads returned a value.

In other words, if your signatures looked like this:

object foo(string s);
object foo(int i);

Then you could do this (you're throwing away the return value, but at least it'll compile):

object o = condition ? foo(0) : foo("");

Anyway, the ol' if/else is your best bet, in this case.

like image 65
Dan Tao Avatar answered Jan 03 '23 02:01

Dan Tao


The method call of foo is determined at compile time, so it cannot call a different method (or overload) based on the result of evaluating the condition. Instead, try something like this:

condition ? foo(0) : foo("")

This way, the compiler will succeed in performing overload resolution and will resolve the first call to foo(int) and the second call to foo(string).

EDIT: As noted by other, you cannot use the ?: operator as a statement, nor can you use methods which return void in it. If your actual methods return compatible types, you could do something like:

int result = condition ? foo(0) : foo("");

If not, you must use an if:

if (condition)
    foo(0);
else
    foo("");
like image 34
Allon Guralnek Avatar answered Jan 03 '23 01:01

Allon Guralnek