Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Would allowing extension methods to be defined in nested classes make sense? #9139

Closed
JohanLarsson opened this issue Feb 24, 2016 · 8 comments

Comments

@JohanLarsson
Copy link

public class Foo
{
    ...
    private static class Bar
    {
        internal static string Baz(this string s)
        {
            ...
        }
    }
}

My thinking is that allowing ^ would be a way to scope extension methods to only be visible in Foo.
Could be nice for extensions on types like string when a limited scope is desired.
I don't remember the reason why extension methods are not allowed in nested classes.
I have not though much about and it may be a bad idea, wrote this to get some feedback.
Would this add much complexity to parsing etc?

@jnm2
Copy link
Contributor

jnm2 commented Jan 6, 2017

Yes! This restriction is frustrating once in a while in general and frustrating frequently in C# scripts like Cake, where there is no way to declare an extension method.

@filipw
Copy link
Contributor

filipw commented Feb 24, 2017

@jnm2

C# scripts have supported extension methods for a while. This is a valid script for example:

static void Hi(this object o) {
    Console.WriteLine("hi " + o);
}

"foo".Hi();

@filipw
Copy link
Contributor

filipw commented Feb 24, 2017

here is the PR #3472

@jnm2
Copy link
Contributor

jnm2 commented Feb 24, 2017

Hmm... thanks for the heads up. The most recent version of Roslyn that Cake uses is 1.0.0-rc2, so that's why I'm still getting CS1106.

@filipw
Copy link
Contributor

filipw commented Feb 24, 2017

that's the last version that supported .NET 4.5. it's also almost 2 years old, with 2.0.0 going RTM soon and 2.0.0-rc4 being the latest

@svick
Copy link
Contributor

svick commented Aug 9, 2017

I think this is a duplicate of #4565 (which was moved to dotnet/csharplang#301).

@OJacot-Descombes
Copy link

Why declare it in a nested static class instead of directly in the class?

public class Foo
{
    ...
    protected static string Baz(this string s) // Always protected or private
    {
        ...
    }
}

@jnm2
Copy link
Contributor

jnm2 commented Sep 27, 2018

Would you close the issue, please, since all language design issues have migrated to https://github.com/dotnet/csharplang?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

7 participants