-2

Is there a way to convert this if/else statement so that it can be called in a more dynamic way without using reflection?

if (left.IsColliding()) directions.Remove(Direction.Left);
else directions.Add(Direction.Left);

In JavaScript I can do the following and I was wondering if there was something similar in C#.

directions[left.IsColliding() ? "Remove" : "Add"](Direction.Left);
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338

3 Answers3

0

Not possible in C#.

What is the problem with your code that It is fine and simple.

The javascript version is ugly and problematic because using strings hard coded to call methods is a potential source of bugs and it is unmaintainable.

But you can write this:

switch ( left.IsColliding() )
{
  case true:
    directions.Remove(Direction.Left);
    break;
  case false:
    directions.Add(Direction.Left);
    break;
}
0

Have a look at Func<T, TResult>

It let's you essential define a function and then call it at a later time.

So you could have functions with your strings Remove and Add as keys to a Dictionary<string, Func<T, TResult>.

You can use a Ternary with the same syntax you mentioned for JavaScript. So you would just use that instead of your if statement.

https://learn.microsoft.com/en-us/dotnet/api/system.func-2?view=netframework-4.8

I think I'm answering your question, but based on some comments in your question (which I am unable to comment on as of yet), I'm slightly concerned I did not.

-1

A ternary operator must return something. You can do something like this to return an Action delegate which has the effect you're looking for:

int a = 5;
int b = 10;
(a == b ? (Action)doThis : doThat)();

Where doThis and doThat are methods.

RyanHx
  • 411
  • 3
  • 10
  • This is potentially a nice solution: It compiles, and it has the desired effect on readability and maintainability. However, it needs to be adapted to call instance methods on the `directions` collection. – 15ee8f99-57ff-4f92-890c-b56153 Sep 27 '19 at 16:52
  • 2
    Instead of copying someone else's answer to a similar question, please vote to close this question as a duplicate instead (this answer is a copy of: https://stackoverflow.com/questions/5490095/method-call-using-ternary-operator) – Rufus L Sep 27 '19 at 17:29