Home

What's wrong with this code?

edited November 2017
In LinqPad 5.25 select "C# Program" and paste this code:
void Main()
{
}

public static class Test
{
	private static void DoSomething()
	{
		var t = typeof(NativeMethods);
	}
}

internal static class Unrelated
{
	public static void Unimportant(this string s)
	{
	}
}

internal class NativeMethods
{
}

Try to run it and get: "CS0122 'NativeMethods' is inaccessible due to its protection level".
Now either delete the Unrelated class or rename the NativeMethods class (and the reference to it). Observe that now the error is gone.

Why?

Comments

  • It's an interesting edge-case. In "C# Program" mode, LINQPad wraps everything in a class called "UserQuery", so that your Main method is valid. This means that any classes that you define become nested classes. However, C# does not allow extension methods to exist in nested classes, so when this occurs, LINQPad extracts all static classes and moves them outside UserQuery. If there are still binding errors, it moves all remaining types (including non-static classes, enums, etc) to outside UserQuery and tries again.

    In this case, the presence of "Unrelated" causes LINQPad to move both "Unrelated" and "Test" outside UserQuery. This should not be a problem, because the resultant binding error should make LINQPad extract "NativeMethods", as well. However, because a class called NativeMethods exists internally in LINQPad, C# reports CS0122 instead of CS0103/CS0246.

    I've added a fix for the next build that recognizes CS0246 as a binding error, so the problem should go away. In the meantime, you can work around this by adding the following to the start of your query:

    #define NONEST

    This tells LINQPad to extract all types, so everything is non-nested.
Sign In or Register to comment.