Sunday, December 06, 2009 9:44 PM Sean Feldman

Syntactic Sugar

clip_image002

Well, I wish there was a way of getting away from SyntaticSugar static class initial point, and be able just to do plain code

Do(() => request.Headers = Headers).If(HeadersExist);

Or even better, this

(request.Headers = Headers).If(HeadersExist);

There’s always hope for next version of C# ;) Filed under: ,

Comments

# re: Syntactic Sugar

Monday, December 07, 2009 1:36 AM by Joe Chung

You can almost do this if you cast the action.

Example:

((Action<string>)(s => Console.WriteLine(s))).If("hello", s => !string.IsNullOrEmpty(s));

public static class Extensions

{

   public static void If<T>(this Action<T> action, T value, Func<T, bool> condition) {

       if (condition(value)) {

           action(value);

       }

   }

}

# re: Syntactic Sugar

Monday, December 07, 2009 7:40 AM by JV

I rather see that as over doing it with fluently, simply because

(request.Headers = Headers).If(HeadersExist);

codes as easy and reads as easy (maybe even worse) then:

If(HeadersExist)

(request.Headers = Headers);

which is already possible.

# re: Syntactic Sugar

Monday, December 07, 2009 8:09 AM by Sean Feldman

@Joe,

Yeap, that works as well, but the noise in front (casting would make it less appealing that anything else that already exists).

@JV,

I agree with you for some case, and for some disagree. Sometimes I want to see all the actions that suppose to happen, without diving into conditional flows. This is where it would be handy to have syntax like that.

# re: Syntactic Sugar

Monday, December 07, 2009 9:05 AM by Mike

This looks like you are turning c# into Yoda speak. To me this is less readable.

# re: Syntactic Sugar

Tuesday, December 08, 2009 3:41 AM by Arnis L.

(request.Headers = Headers).If(HeadersExist);

this looks cool.

# re: Syntactic Sugar

Wednesday, December 09, 2009 11:53 AM by FreshFrince

I agree with Mike.  What difference is there really.  You still have an "If".  In general I like syntactic sugar, but only when it makes a clear difference in readability.

If you want to get rid of the "if" look at other ways to change your design.