Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use IEnumerable as return type for an array?

Tags:

c#

I have the following code to optimize execution time and only search for types once:

internal static Type[] SpecTestClasses =
        AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(t => t.GetTypes())
            .Where(t =>
                t.GetCustomAttribute<CompilerGeneratedAttribute>() == null &&
                t.GetCustomAttribute<TestClassAttribute>() != null &&
                t.GetCustomAttribute<SerialSeleniumTestAttribute>() != null)
            .ToArray();

I used to have:

internal static IEnumerable<Type> SpecTestClasses =
        AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(t => t.GetTypes())
            .Where(t =>
                t.GetCustomAttribute<CompilerGeneratedAttribute>() == null &&
                t.GetCustomAttribute<TestClassAttribute>() != null &&
                t.GetCustomAttribute<SerialSeleniumTestAttribute>() != null);

But that didn't optimize my execution since CurrentDomain was queried for each call. So I then added .ToArray(), and then changed the return type to Type[].

Now to my question: What return type should I have? Should I have kept the return type as IEnumerable and if so why? ReSharper didn't have any suggestions on the issue.

Thanks,
Drutten

Edit: For clarification, GetAssemblies() will not change during the applications lifetime.

like image 566
magnusarinell Avatar asked Jun 03 '26 21:06

magnusarinell


1 Answers

Since it's internal, I'd probably use Type[] because the many bad things that can happen if someone changes the array can be avoided by not changing the array.

If it was public, I'd wrap it in a ReadOnlyCollection<Type>. Then I'd have to decide on whether the convenience to the user of my exposing it as that, IReadOnlyList<T> or IList<T> outweighed the burden of my having to continue to support that from then on, while IEnumerable<Type> gives me more freedom to change implementation down the line.

like image 187
Jon Hanna Avatar answered Jun 06 '26 10:06

Jon Hanna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!