c# - An expression that's equivalent to the return keyword -
void foo() { var xmaybenull = getx(); if (xmabyenull == null) return; // way rid of // sentence without loosing check // stuff }
the easy way this, compiler expects expression.
void foo() { list<disc[,]> xnevernull = getx() ?? return; // stuff }
the question is, there way write somesortofreturnexpression
(i guess not) or solution, can i'm looking on 1 line?
void foo() { list<disc[,]> xnevernull = getx() ?? somesortofreturnexpression; // stuff }
this isn't possible envisioned in c# because of non-"functional syntax". (please see notes @ bottom). while conditional operator (?:
) can used in trivial places, runs limits. and, others have pointed out, coalesce operator (??
) carries forward expression, doesn't support "else" case. c# functions must use conventions achieve similar semantics. following discusses approach problem.
--
with few exceptions, i not use returns functions. while c# doesn't have "functional syntax", still find style of code reads start of function end of function clear -- is, last statement of last level of branches (possibly nested) can return function, though conditional (if/else if/else
) expression (like ?:
) return
ed value. (if there many branches, may sign function large.)
in cases write code following:
void foo() { var xmaybenull = getx(); if (xmabyenull != null) { // know it's valid use xmaybenull in here -- can't null. // "do stuff" } // xmaybenull may null here. don't put here // requires otherwise. in case flow "drop off" // `return` omitted. }
since follow pattern consistently helps me read/understand code , flow better. approach avoids "being tricky" , extend handle "null case" adding else
end. keeping assignment first , separate keeps code simpler , allows use of var
, find nice.
happy coding.
the 1 case push condition , function exit raised exceptions in guards...
if (argx == null) throw new argumentnullexception("argx");
...but such nature of exceptions.
actually, can done extension methods in manner similar smalltalk. however, in case, introduce more complications. don't keep cleverness goggles on long. imagine:
public static void ifnotnull<t>(this t it, action<t> action) { if (it != null) action(it); } getx().ifnotnull((x) => { // "do stuff", x can't null });
Comments
Post a Comment