-2

I implemented Array.Empty<T> because want to use this code

foreach (Control c in controls.OrEmptyIfNull())
{
    this.Controls.Add(c);
}

OrEmptyIfNull extension method

but my program is using .NET version 4.5 and I don't want to change.

Array.Emtpy

so coded below

public static class ExtensionClass
{
    public static T[] Empty<T>(this Array array)
    {
        return EmptyArray<T>.Value;
    }

    public static IList<T> OrEmptyIfNull<T>(this IList<T> source)
    {
        return source ?? Array.Empty<T>();
    }

    internal static class EmptyArray<T>
    {
        public static readonly T[] Value = new T[0];
    }
}

but an error occurred this line return source ?? Array.Empty<T>();

Error CS0117 'Array' does not contain a definition for 'Empty'

how to use Array.Empty() or check before foreach List is null much prettier

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
  • Why not use standard LINQ? `public static IEnumerable OrEmptyIfNull(this IEnumerable source) => source ?? Enumerable.Empty();` – Enigmativity Nov 03 '20 at 03:47

2 Answers2

1

Since Array.Empty<T> is only available from .Net 4.6 + you could easily just new up a List<T> or new T[0]; both of which implement IList<T>

return source ?? new List<T>();

// or

return source ?? new T[0];

It's also worth a note, that the source code for Array.Empty<T> basically just references a static type for minimal allocations, so you could replicate this functionality fairly easily:

internal static class EmptyArray<T>
{
    public static readonly T[] Value = new T[0];
}

...

return source ?? EmptyArray<T>.Value;

Note : I would be skeptical about any of these extension methods considering the move to nullable types. However, since you are stuck in the 2012's there is probably little harm :)

halfer
  • 19,824
  • 17
  • 99
  • 186
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
0

You already have EmptyArray<T> defined, why not just use it?

return source ?? EmptyArray<T>.Value;
shingo
  • 18,436
  • 5
  • 23
  • 42