One idiom in C# to 'create a value on first access'1 is to use something like the following2:
public string X {
get {
return _x ?? (_x = MakeX());
}
}
Given a slight variation, where MakeX
is defined as void MakeX(out string x)
instead of the "standard" string MakeX()
, is there a way to leverage C# [7] syntax shortcuts?
(There are a million ways to re-write the code3; the question is primarily about, if there are any new tricks that allow an 'out statement' to be used in an expression.)
The following does not work (it might be worse than that1..) but here is the gist:
public string X {
get {
return _x ?? { MakeX(out _x); _x };
}
}
The semantic long form (which is valid..) would look something like:
public string X {
get {
var x = _x;
if (x != null) return x;
MakeX(out x);
return (_x = x);
}
}
1It is assumed that thread-safety is not relevant as long as a value is returned. No suggestions for Lazy
:}
2The original-style get
is not in question.
3The question is about new syntax in particular, not doing "overly clever tricks" with lambdas. As such, return _x ?? (() => {MakeX(out _x); return _x;})();
would still result in a "no" to the question.