4

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.

user2864740
  • 60,010
  • 15
  • 145
  • 220
  • 2
    Wow you took all the fun out of this question – TheGeneral Jul 29 '18 at 04:53
  • 4
    The answer is no unfortunately. Since `MakeX` is a `void`, you cant use it in a null-coalescing operator without funky lamdas – TheGeneral Jul 29 '18 at 05:02
  • 1
    If you're willing to define `MakeX` as `string MakeX(out string x)` and make it always return `null`, then you could write this: `return _x ?? MakeX(out _x) ?? _x;`. Note that it's confusing, and you can't really beat the *idiomatic* `return _x ?? (_x = MakeX());` – Lucas Trzesniewski Jul 29 '18 at 21:23
  • @LucasTrzesniewski In that case, it could be written as `return _x ?? MakeX(out _);` with the ["dummy out" feature](https://stackoverflow.com/questions/42920622/c7-underscore-star-in-out-variable). I was hoping for / to discover additional 'out'-as-expression support :} – user2864740 Jul 29 '18 at 21:32

0 Answers0