RameshVel
RameshVel

Reputation: 65887

Extending the Enumerable class in c#?

I have situation to extend the Enumerable class in c# to add the new Range method that accepts long parameters. I cannot define the method like this

public static IEnumerable<long> Range(this Enumerable source, long start, long length)
{
    for (long i = start; i < length; i++)
    {
        yield return i;
    }
}

Since extension methods are accesible only through its objects. And it gives me an error

'System.Linq.Enumerable': static types cannot be used as parameters

Can someonce clarify me how to do this

Note: I know we can easily solve this without extension methods, but i needed this Enumrable class.

Upvotes: 5

Views: 5345

Answers (5)

LukeH
LukeH

Reputation: 269638

Extension methods can only be called on instances of a type, and since Enumerable is a static type there will never be any instances of it, which means that you can't extend it.

It makes no sense to have your Range method as an extension on IEnumerable<T> either. Your method just generates a sequence of long values, it doesn't need to extend any particular instance.

Use a standard static utility method instead:

var example = EnumerableUtils.Range(0, long.MaxValue).Where(x => (x % 2) == 0);

// ...

public static class EnumerableUtils
{
    public static IEnumerable<long> Range(long start, long count)
    {
        for (long i = start; i < start + count; i++)
        {
            yield return i;
        }
    } 
}

Upvotes: 5

Sebastian P.R. Gingter
Sebastian P.R. Gingter

Reputation: 6085

Why do you want to extend System.Linq.Enumerable? This class uses Extension methods to extend OTHER types that implement IEnumerable.

The result would be, that you'd call:

Enumerable.Range(long, long);

You'd rather extend the long class directly:

public static IEnumerable<long> Range(this long source, long length)
{
    for (long i = source; i < length; i++)
    {
        yield return i;
    }
}

This way you can start with

foreach (long item in 10.Range(20)) { }

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1064114

You're going to have to create your own utility class for that; you can'd add static methods via extension methods.

Upvotes: 0

Matt Hamilton
Matt Hamilton

Reputation: 204259

You (like me) are looking for static extension methods:

http://madprops.org/blog/static-extension-methods/

It's not possible in C#. The closest alternative is to define another static class with a similar name (LongEnumerable?) and add your static method to that.

Upvotes: 8

configurator
configurator

Reputation: 41670

You can't extend the Enumerable class, since you don't have an Enumerable instance - it's a static class. Extension methods only work on instances, they never work on the static class itself.

Upvotes: 0

Related Questions