Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# Introduction

Iskander Ismagilov
Iskander Ismagilov
13,298 Points

Make an array extension

Does it turn out that you can't make extension method for array of any type cause array is not a generic type?

1 Answer

Hi, Iskander! In C# you can create an extension for any collection type (not necessarily generic). As simple example:

public static class Extensions 
{
    public static T Extension<T>(this T array) where T : IEnumerable
    {
        // do something
        return array;
    }

    public static int[] Extension(this int[] array) 
    {
        // do something
        return array;
    }
}   
Iskander Ismagilov
Iskander Ismagilov
13,298 Points

Thank you, Max! Your example with type constraint helped me to understand how to make extensions for array. Also, previously I was confused about treating array as IEnumerable<T>, but then I found that array do implements IEnumerable<T> from the doc.