Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I define top-level extension methods in C# 9?

Tags:

c#

c#-9.0

I had thought that using the Top-Level Statements feature in C# 9 essentially wraps your top-level code in the usual Program class and Main method.

A decompiled top-level program looks like this:

[CompilerGenerated]
internal static class $Program
{
    private static void $Main(string[] args)
    {
        // top-level code here
    }
}

You can define normal methods at the top-level. They are compiled into the Program class, but outside of the Main method, where extension methods can also be defined.

Because the generated Program class is static and non-generic, I would expect to be able to define extension methods at the top level. However, I get compiler error CS1106: Extension method must be defined in a non-generic static class

VS Code compiler error CS1106: Extension method must be defined in a non-generic static class

Why is this?

like image 628
Connell Avatar asked Dec 03 '22 17:12

Connell


1 Answers

The C# Language Specification says:

When the first parameter of a method includes the this modifier, that method is said to be an extension method. Extension methods can only be declared in non-generic, non-nested static classes.

According to the language specification, extension methods must be declared in a static class.

It does not matter that top-level methods are implemented by placing them in a hidden static class. Top-level methods are (by definition) not declared in any class, and therefore cannot be extension methods according to the specification.

As with all language design questions, this is the way that it is because this is the way that the language design team designed the language. Presumably the same concerns which prevent you from defining extension methods inside non-static classes also apply to top-level methods.

You can open a discussion in the csharplang repo or ask a question on Gitter if you want someone with more authority to possibly give more detail.

like image 192
canton7 Avatar answered Dec 26 '22 15:12

canton7