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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With