Posts

Showing posts with the label null-coalescing-operator

Null coalescing operator IList, Array, Enumerable.Empty in foreach

In this question I found the following: int[] array = null; foreach (int i in array ?? Enumerable.Empty<int>()) { System.Console.WriteLine(string.Format("{0}", i)); } and int[] returnArray = Do.Something() ?? new int[] {}; and ... ?? new int[0] In a NotifyCollectionChangedEventHandler I wanted to apply the Enumerable.Empty like so: foreach (DrawingPoint drawingPoint in e.OldItems ?? Enumerable.Empty<DrawingPoint>()) this.RemovePointMarker(drawingPoint); Note: OldItems is of the type IList And it gives me: Operator '??' cannot be applied to operands of type 'System.Collections.IList' and System.Collections.Generic.IEnumerable<DrawingPoint> However foreach (DrawingPoint drawingPoint in e.OldItems ?? new int[0]) and foreach (DrawingPoint drawingPoint in e.OldItems ?? new int[] {}) works just fine. Why is that? Why does IList ?? T[] work but IList ?? IEnumerable<T> doesn't? When using this expression: a ?? b Then b e...