Proposal: Extension method support in scripting
See original GitHub issueProblem
Developers using C# scripting are unable to define extension methods in script. I believe this is due to the fact that the script code is wrapped in the submission, and you cannot have extensions on nested static classes. Also Roslyn does not allow using “this”
For example, a developer cannot do this within a script.
public static class StringExtensions() {
public static string DoSomething(this string text ) {
...
}
}
Now extension methods can be defined on dlls and loaded into the scripting context, however this requires a developer to create a full blown C# project / dll. It would offer a smoother scripting experience if these extension methods could be defined within a top-level script, or a child script that is loaded with #load
.
Proposed solutions
Both solutions would require allowing usage of the this
pointer in script, OR some equivalent. If this
is enabled, it could be scoped to only work for extension methods if there is concern about its usage elsewhere.
A. Support extension methods on nested classes.
If extension methods are enabled on nested static classes, then one could define a static class in script with extensions and they would be picked up. This would make the above example work, though I imagine it will be more work to allow this at the compiler level.
B. Lift the class at compile time
Provide a new #extensions
directive which can be put on a class to indicate that this class has extension methods. At compile time the class is lifted out of the submission so that the extension methods can be resolved.
Here is an example of how this would look from an authoring perspective
#extensions
public static class StringExtensions() {
public static string DoSomething(this string text ) {
...
}
}
Issue Analytics
- State:
- Created 9 years ago
- Comments:10 (5 by maintainers)
Top GitHub Comments
My opinion is that we should allow to define extension methods in any class in C# proper.
👍