dotnet / dotnet/fsharp

Calling protected static base member from static do raises MethodAccessException

Open
#11,929 3 comments 0 reactions 0 assignees View on GitHub
Area-Compiler-Checking Area-Compiler-Checking-Accessibility Area-Compiler-CodeGen Bug Impact-Medium
Dominant language
F#
Stars
4.3k
Forks
876
Avg merge
4d 11h
Merged PRs (30d)
131

Description

If the `static do` block of a class attempts to call a `protected static` member of a base class, a MethodAccessException is raised because the code from the do block is moved outside the derived class by the compiler

```fsharp
#nowarn "44" // using Uri.EscapeString just because it's protected static

type C(str : string) =
inherit System.Uri(str)

static do
System.Uri.EscapeString("data") |> ignore

C("hello") |> ignore
```
[Sharplab example](https://sharplab.io/#v2:DYLgZgzgNALiBOBXAdlAJiA1AHwMTIHsB3AQ3mQAIAiAFhqooHpGLEIBLZAcwoFV52AOgCiEAMYkADgFMAyjAHcKAKzYwKAI2kS20iuxgByCBUnwCMbZbQUIMEjHZiAsACg3MAJ4yKAYQAUdvAUILYKnFwAlBQAvG4UCfrIABbSAuqynnbSALaC/OyBCpHxiaUJdg5OFGgE5YkJmdl5BSLiUnLh3P5UaA4kVNHYAHz6XITw0m5uAVSpwMAEgxQjYxPSQA===)

**Expected behavior**

The method call should succeed, since the `static do` is the equivalent to C#'s static constructor, or a warning should be produced that while this will compile it won't work.

**Actual behavior**

A `MethodAccessException` is raised on the call

**Known workarounds**
Move the method call into a static member of the derived class, and call it from the `static do` block:
```fsharp
static do
C.Do()

static member internal Do() =
System.Uri.EscapeString("data") |> ignore
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.