Using extension methods in RoslynPad

I am trying to understand an extension method similar to this code

var p = new Person("Tim"); p.LastName = "Meier"; // reader.Get<bool>("IsDerivat"); var IsOlivia = p.Get<bool>("Olivia"); 

This is my code inside RoslynPad :

 public static class PersonExtensions { public static T Get<T>(this Person person, string name) { return (T)person.NewFirstName(name); } } public class Person { public Person(string firstName) { this.FirstName = firstName; } public string FirstName {get; private set;} public string LastName {get; set;} public object NewFirstName(string name) { this.FirstName = name; return (object) this.FirstName; } } 

But I get this error

bug CS1109: extension methods must be defined in the static static level class; PersonExtensions is a nested class

I found this question extension-methods-must-be-defined-in-a-top-level-static-class- and the answers are good.

Adding namespace Foo returns

error CS7021: cannot declare namespace in script code

Roslynpad seems to add things backstage. So, how can I make sure my extension method is defined in a top-level static class?

+5
source share
2 answers

RoslynPad uses a Roslyn script language syntax that does not allow extension methods in classes (since the entire script is actually a class, and C # does not allow extensions in nested classes).

Currently, your only option (besides referencing a compiled assembly that contains the extension class using the #r directives) is to place the extension as a top-level method in the script. For instance:

 public static T Get<T>(this Person person, string name) { return (T)person.NewFirstName(name); } var p = new Person("Tim"); p.LastName = "Meier"; var IsOlivia = p.Get<bool>("Olivia"); // works 

PS - I am the author of RoslynPad.

+9
source

To be considered a top-level class, the class must be defined inside namespace . Move the declarations of the Person and PersonExtensions classes to the namespace, and this will fix the problem.

So:

 namespace MyPersonNamespace { public static class PersonExtensions { public static T Get<T>(this Person person, string name) { return (T)person.NewFirstName(name); } } public class Person { public Person(string firstName) { this.FirstName = firstName; } public string FirstName {get; private set;} public string LastName {get; set;} public object NewFirstName(string name) { this.FirstName = name; return (object) this.FirstName; } } } 
0
source

Source: https://habr.com/ru/post/1259299/


All Articles