Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 782
TJB Avatar asked Jun 05 '13 19:06

TJB


People also ask

How do you declare an extension method?

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.

Can we define extension method for a class?

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.

What keyword is used to define an 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.

How do you use an extension method?

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.


1 Answers

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.

like image 86
Glenn Block Avatar answered Oct 04 '22 07:10

Glenn Block