I\'m asking with regards to c#, but I assume its the same in most other languages.
Does anyone have a good definition of expressions and statements
A statement is a special case of an expression, one with void
type. The tendency of languages to treat statements differently often causes problems, and it would be better if they were properly generalized.
For example, in C# we have the very useful Func
overloaded set of generic delegates. But we also have to have a corresponding Action
set as well, and general purpose higher-order programming constantly has to be duplicated to deal with this unfortunate bifurcation.
Trivial example - a function that checks whether a reference is null before calling onto another function:
TResult IfNotNull(TValue value, Func func)
where TValue : class
{
return (value == null) ? default(TValue) : func(value);
}
Could the compiler deal with the possibility of TResult
being void
? Yes. All it has to do is require that return is followed by an expression that is of type void
. The result of default(void)
would be of type void
, and the func being passed in would need to be of the form Func
(which would be equivalent to Action
).
A number of other answers imply that you can't chain statements like you can with expressions, but I'm not sure where this idea comes from. We can think of the ;
that appears after statements as a binary infix operator, taking two expressions of type void
and combining them into a single expression of type void
.