fsharp icon indicating copy to clipboard operation
fsharp copied to clipboard

Calling protected static base member from static do raises MethodAccessException

Open marklam opened this issue 4 years ago • 3 comments

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

#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

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:

    static do
        C.Do()

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

marklam avatar Aug 09 '21 09:08 marklam

I should add the real-world case - calling Visual.AffectsRender in an Avalonia custom control class derived from Border.

marklam avatar Aug 09 '21 09:08 marklam

Hmmm yes this should be allowed. Thanks

dsyme avatar Aug 10 '21 22:08 dsyme

Note: This is fixed by enabling --realsig+. Might be worth adding a tests for this specific scenario.

edgarfgp avatar Aug 02 '24 14:08 edgarfgp