c# - Why the ternary operator is not working this way? -


why not compile? wrong in following code?

(_dbcontext == null) ? return _dbcontext = new productandcategoryentities() : return _dbcontext; 

if restate in terms of if compiles:

 if (_dbcontext == null)                    return _dbcontext = new productandcategoryentities();                else return _dbcontext; 

the things on either side of : in conditional expression expressions, not statements. must evaluate value. return (anything) statement rather expression (you can't x = return _dbcontext;, example), doesn't work there.

new productandcategoryentities() , _dbcontext both seem expressions, though. can move return outside of conditional expression.

return (_dbcontext == null) ? (_dbcontext = new productandcategoryentities()) : _dbcontext; 

although, in case, it'd better lose ?: , go straight if.

if (_dbcontext == null) _dbcontext = new productandcategoryentities(); return _dbcontext; 

which bit more straightforward. returning value of assignment looks bit sketchy.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -