Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Extension methods in RoslynPad

I try 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

error CS1109: Extension methods must be defined in a top level static 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 a namespace Foo returns

error CS7021: Cannot declare namespace in script code

It seems that roslynpad adds stuff behind the scene. So how can i make sure that my extension method is defined in a top-level static class?

like image 416
surfmuggle Avatar asked Nov 04 '16 19:11

surfmuggle


1 Answers

RoslynPad uses Roslyn's script language syntax, which does not allow extension methods in classes (because the entire script is actually a class, and C# doesn't allow extensions in nested classes).

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

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'm the author of RoslynPad.

like image 193
Eli Arbel Avatar answered Sep 28 '22 17:09

Eli Arbel