6 ms·
Slight aside: please don't abuse the Elvis operator like that (by using it on every single nullable reference), it could easily grow into a widespread anti-patt
by piaste 10y ago
Slight aside: please don't abuse the Elvis operator like that (by using it on every single nullable reference), it could easily grow into a widespread anti-pattern that makes debugging harder.
My rule of thumb is that ?. is OK to use when
1) The reference is expected to occasionally be null in the course of normal operations
2) You legitimately don't care if the reference is unexpectedly null, as you wouldn't or couldn't fix it even if you knew about it
Otherwise it's better to discover and fix the NullReferenceException ASAP.
- perezdev 10y agoIt's the null propagation operator.
- breischl 10y agoLook, if you want to be pedantic it's the null conditional operator[1]. But it is widely called the "Elvis operator"[2]. [1] - https://msdn.microsoft.com/en-us/library/dn986595.aspx https://msdn.microsoft.com/en-us/library/dn986595.aspx [2] - https://www.google.com/#q=c%23+elvis+operator https://www.google.com/#q=c%23+elvis+operator
- gregmac 10y agoGenerally agreed, and out of curiosity I just looked through some fairly new code I have that's pretty heavy on C# 6, and only found a single instance of two null conditionals being used: Assert.That(r.Exception?.InnerException?.Message, Is.EqualTo("Exception result")); Next closest thing that shows up a few times is coalescing to a default value: config?.OutputName ?? DefaultConfig.OutputName Some other examples that show up a lot: Invoke Action<> or Func<> that may be null or unassigned (this works for Events as well): actionHandler?.Invoke(value); Extracting a value from a LINQ expression on a list of container objects (this one is actually from a unit test where it's explicitly only expecting one item): items.First()?.Data Easy way to do a Coalesce on a specific property value in a collection: items.FirstOrDefault(item => item.Data != null)?.Data
- piaste 10y agoitems.First()?.Data I think this one doesn't do anything because .First() will throw on an empty collection. The rest of your samples look fine to me though.