Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Add custom method to Lists

I would like to add a method to extend my List behavior, but I'm having trouble. I would like have the 'extension' method in the class where I'm working on it. How can I do it?

I want to do:

class MyClass
{
    public void DoSomething()
    {
        List<string> myList = new List<string>()
        myList.Add("First Value");
        myList.AddMoreValues(); //or myList += AddMoreValues()  ??
    }        

    private void AddMoreValues(this List<string> theList)
    {
        theList.Add("1");
        theList.Add("2");
        ...
    }
}

The code above gives me the error:

Extension method must be defined in a non-generic static class

like image 415
Cameron Castillo Avatar asked Sep 20 '25 10:09

Cameron Castillo


1 Answers

Extension methods must be static to use them how you want to use them. Simply add the static keyword to your method:

private static void AddMoreValues(this List<string> theList)

But you're better off putting it in a separate static class and making it public (it's easier to organise your extension methods that way), something like:

public static class ListExtensions
{
    public static void AddMoreValues(this List<string> theList)
    {
        theList.Add("1");
        theList.Add("2");
        ...
    }
}

Extension methods need to be in a static class as per section 10.6.9 of the C# spec:

When the first parameter of a method includes the this modifier, that method is said to be an extension method. Extension methods can only be declared in non-generic, non-nested static classes. The first parameter of an extension method can have no modifiers other than this, and the parameter type cannot be a pointer type.

like image 180
mattytommo Avatar answered Sep 23 '25 00:09

mattytommo