-4

I have this in my class:

public delegate void OnTrue(String TestPassed);
public event OnTrue OnTrueEvent;

public delegate void OnFalse(String TestPassed);
public event OnFalse OnFalseEvent;

This is my Do method:

public void Do()
{
   bool found=false;
   string p ="";

   // some actions

   found ? (OnTrueEvent != null ? OnTrueEvent(p): ;) :(OnFalseEvent != null ? OnFalseEvent(p): ;);
}

The problem that if in line does not work.

Exploded it should be this:

if (found)
   if (OnFalseEvent != null)
      OnFalseEvent(p);
else
   if (OnTrueEvent != null)
      OnTrueEvent(p);

I would like to know where you are wrong and how correct it should be.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

4

exploded it should be this:

and there-in is the error; no, it shouldn't. The conditional operator is always an expression, not a statement. It has no defined meaning in the way you've used it.

If you mean if/else: use if/else.

Note that you can simplify some of the code, though:

(found ? OnFalseEvent : OnTrueEvent)?.Invoke(p);

This works because the conditional part is used as an expression - meaning: the value is consumed. In this case, it is consumed by the null-coalescing invoke.

Note that this would only work if OnFalseEvent and OnTrueEvent have the same delegate type, which they probably should. Action<string> would work fine. If they don't, you'll need the longer:

if(found)
    OnTrueEvent?.Invoke(p);
else
    OnFalseEvent?.Invoke(p);

(your choice of braces and indentation is left as an exercise for the reader)

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

As an aleternative for null checking you can assign the fields into do nothing:

public delegate void OnTrue(String TestPassed);
public event OnTrue OnTrueEvent = (item) => { }; // do nothing; not null

public delegate void OnFalse(String TestPassed);
public event OnFalse OnFalseEvent = (item) => { }; // do nothing; not null

...

public void Do() {
  ...

  // No need to check for null here
  if (found) 
    OnFalseEvent(p);
  else
    OnTrueEvent(p); 
}

Since OnTrue and OnFalse are different types you can't put it as

(found ? OnFalseEvent : OnTrueEvent)(p);

since ? : must return the same type for both branches

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215