I'm playing with ScriptCS (which is awesome!) but I couldn't figure out how to define an extension method within a .csx script file.
Take this example:
using System.IO;
public static class Extensions
{
public static string Remove(this string source, params string[] toRemove)
{
foreach(var r in toRemove)
{
source = source.Replace(r,"");
}
return source;
}
}
string[] entries =
Directory
.GetFiles(
@"C:\Users\blah\blah",
"*.mp4",
SearchOption.AllDirectories)
.Select( p => p.Remove("Users"))
.ToArray();
foreach(var e in entries)
{
Console.WriteLine(e);
}
This yields the error:
error CS1109: Extension methods must be defined in a top level static class; Extensions is a nested class
I'm guessing that ScriptCS wraps the csx in some class which is causing extensions to be nested, is there any way around this?
An extension method must be defined in a top-level static class. An extension method with the same name and signature as an instance method will not be called. Extension methods cannot be used to override existing methods. The concept of extension methods cannot be applied to fields, properties or events.
It must be defined in top-level static class. Multiple binding parameters are not allowed means an extension method only contains a single binding parameter. But you can define one or more normal parameter in the extension method.
Extension Method uses the "this" keyword as the first parameter. The first parameter always specifies the type that the method operates on. The extension method is written inside a static class and the method is also defined as static.
To define an extension method, first of all, define a static class. For example, we have created an IntExtensions class under the ExtensionMethods namespace in the following example. The IntExtensions class will contain all the extension methods applicable to int data type.
I feel your pain.
Actually this is a limitation of Roslyn currently as it wraps everything into a class even if it is another class.
I've talked to the Roslyn team however and they are going to support extension methods soon.
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