Search code examples
c#.netextension-methodsscriptcs

How to define an extension method in a scriptcs csx script


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?


Solution

  • 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.