Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby-like 'unless' for C#?

Is there any way to do something similar in C#?

ie.

i++ unless i > 5;

here is another example

weatherText = "Weather is good!" unless isWeatherBad
like image 478
Konstantinos Avatar asked Apr 24 '12 08:04

Konstantinos


2 Answers

You can achieve something like this with extension methods. For example:

public static class RubyExt
{
    public static void Unless(this Action action, bool condition)
    {
        if (!condition)
            action.Invoke();
    }
}

and then use it like

int i = 4;
new Action(() => i++).Unless(i < 5);
Console.WriteLine(i); // will produce 4

new Action(() => i++).Unless(i < 1);
Console.WriteLine(i); // will produce 5

var isWeatherBad = false;
var weatherText = "Weather is nice";
new Action(() => weatherText = "Weather is good!").Unless(isWeatherBad);
Console.WriteLine(weatherText);
like image 153
avivr Avatar answered Sep 21 '22 12:09

avivr


What about :

if (i<=5) i++;

if (!(i>5)) i++; would work too.


Hint : There is no unless exact equivalent.

like image 45
Dr.Kameleon Avatar answered Sep 22 '22 12:09

Dr.Kameleon