samedi 18 novembre 2017

Why doesn't C# allow free standing expressions inside of functions?

In many programming languages, free standing expressions are allowed inside of functions and they really get evaluated. Using expressions to short the code comes in very handy when you are lazy or when you don't have much time to finish a project. For example, the && operator uses short-circuit evaluation and this is very useful.Instead of

if(hasLost())
  print("You Lost!")

one can just write

hasLost() && print("You Lost!")

When it comes to C#, expressions that are not increment, decrement, function call, await or new object expressions are not allowed to stand alone. Why does C# do that? Are there any workarounds on this?

One workaround would probably be creating a function with a very short name that doesn't do anything or just returns something like the void operator in Javascript.

void ev(bool expr) { return null } 
ev(hasLost() && print("You Lost!")) ;

However, this is almost as long as using an if statement. The real advantages can only be seen when you are working with a generalized alternative structure. Are using workaround like this really worth it? Should I use them or should I stick to a normal if statement.

Aucun commentaire:

Enregistrer un commentaire