-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

1
  • Why not use standard LINQ? public static IEnumerable<T> OrEmptyIfNull<T>(this IEnumerable<T> source) => source ?? Enumerable.Empty<T>(); Commented Nov 3, 2020 at 3:47

2 Answers 2

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 :)

Sign up to request clarification or add additional context in comments.

Comments

0

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

return source ?? EmptyArray<T>.Value;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.