jchang
jchang

Reputation: 31

Is there a way to create a method for a generic collection of a custom class in C#?

I was wondering if this was at all possible. Since I´m not all right there with IEnumerator/IEnumerables, there might be a way to do it I don´t know. I imagine it would go something like this:

public namespace cookietest
{
    public static class Program{
        public List<Cookie> cookies = new List<Cookie>();
        CookieJar cookieJar = cookies.ToCookieJar();
    }

    public class Cookie{
        public int size;
        //Implementatin of ToCookieJar()
    }
}

I understand that there are better design solutions and that this isn't really a problem, but I got curious and couldn't find anything about it.

Upvotes: 0

Views: 95

Answers (1)

Peter Lillevold
Peter Lillevold

Reputation: 33930

What you are looking for is called extension methods.

Given a reference type, such as List<T>, you can "extend" it with your own methods like this:

public static class Program
{
    public List<Cookie> cookies = new List<Cookie>();
    CookieJar cookieJar = cookies.ToCookieJar();
}

public class Cookie
{
    public int size;
}

public static class CookieExtensions
{
    public static CookieJar ToCookieJar(this IEnumerable<Cookie> list)
    {
        return new CookieJar(list);
    }
}

Upvotes: 1

Related Questions