Skip to content

static constructors throw NRE if having struct fields and invoked via TypeInitializer #1748

Closed

Description

@ufcpp

The following code throws NullReferenceException on .NET Core (doesn't throw on .NET Framework).
It this a bug?

using System;

struct S { }

class A
{
    static TimeSpan x = default; // throws NRE
    // FYI, generated il is: ldsflda, initobj
}

class B
{
    static S x = default; // throws NRE
}

class C
{
    static S x;
    static C() => x = default; // throws NRE
}

class D
{
    // no exception if static fiealds are primitives or reference types
    // generated il is: ldnull/ldc.i4, stsfld
    static string x = null;
    static int y = 0;
}

static class Program
{
    static void Main()
    {
        Console.WriteLine("----");
        try { typeof(A).TypeInitializer.Invoke(null, null); } catch { Console.WriteLine("A"); } // A
        try { typeof(B).TypeInitializer.Invoke(null, null); } catch { Console.WriteLine("B"); } // B
        try { typeof(C).TypeInitializer.Invoke(null, null); } catch { Console.WriteLine("C"); } // C
        try { typeof(D).TypeInitializer.Invoke(null, null); } catch { Console.WriteLine("D"); } // (no excpetion)

        Console.WriteLine("----");
        A a = new A();
        B b = new B();
        C c = new C();
        try { typeof(A).TypeInitializer.Invoke(null, null); } catch { Console.WriteLine("A"); } // A
        try { typeof(B).TypeInitializer.Invoke(null, null); } catch { Console.WriteLine("B"); } // B
        try { typeof(C).TypeInitializer.Invoke(null, null); } catch { Console.WriteLine("C"); } // (no excpetion)
        try { typeof(D).TypeInitializer.Invoke(null, null); } catch { Console.WriteLine("D"); } // (no excpetion)
    }
}

Activity

  1. added
    untriaged
    on Jan 15, 2020
  2. changed the title [-]static constructors throw NRT if having struct fields and invoked via TypeInitializer[/-] [+]static constructors throw NRE if having struct fields and invoked via TypeInitializer[/+] on Jan 15, 2020
  3. jkotas commented on Jan 15, 2020

    @jkotas
    Member

    Yes, this looks like a bug.

  4. jkotas commented on Jan 15, 2020

    @jkotas
    Member

    We are missing allocation of boxed statics on this path (look for HasBoxedRegularStatics).

  5. added this to the 5.0 milestone on Jan 30, 2020
  6. removed
    untriaged
    on Jan 30, 2020
  7. self-assigned this
    on Aug 3, 2020
  8. ghost locked as resolved and limited conversation to collaborators on Dec 11, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions