Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static constructor called more than once

Tags:

c#

using System;

namespace ConsoleApplication15
{
  using System.Collections.Generic;
  using System.Threading;

  public static class Program
  {
    static void Main(string[] args)
    {
      var test1 = new Test<List<int>>();
      var t = new Thread(Tester);
      t.Start();

      var test2 = new Test<List<int>>();
      var test3 = new Test<List<int>>();
      var test4 = new Test<List<int>>();
      var test5 = new Test<List<int>>();


      test1.Do();
      test2.Do();
      test3.Do();
      test4.Do();
      test5.Do();
    }

    private static void Tester()
    {
      var test5 = new Test<IList<int>>();
      test5.Do();
    }
  }

  public class Test<T> where T : IEnumerable<int>
  {

    private static Something something;

    static Test()
    {
      Console.WriteLine("IM  static created ");

      something = new Something();
      Console.WriteLine(something.ToString());
    }

    public Test()
    {
      Console.WriteLine("IM  created ");
    }

    public void Do()
    {
      Console.WriteLine("Do something! ");
    }
  }

  public class Something
  {
    public Something()
    {
      Console.WriteLine("Create something");
    }
  }
}

When I run the the above code I have exptected that the static construcor in static Test() shall be called one time but when I ran the code the static construcor is called twice!!!!!

When I remove the this line <T> where T : IEnumerable<int> everything working fine(static construcor called once)?!!!!

This is the breakpoint for the first callThis is the breakpoint for the second call

like image 210
Bassam Alugili Avatar asked Mar 20 '23 06:03

Bassam Alugili


2 Answers

The static is per type, and a generic type creates a new type for each different T you specify.

Basically, each closed generic is a type in and of itself, regardless of being defined from a generic template.

This is a common gotcha with static members.

like image 199
Adam Houldsworth Avatar answered Apr 02 '23 09:04

Adam Houldsworth


In C#, specific parameterizations of a generic type are actually unique types. This is the advantage of preserving generic type information as part of the runtime, as opposed to languages like Java that remove generic type information during the compilation process.

There are many use cases for static constructors in generic types, such as the following: https://stackoverflow.com/a/15706192/138304

Another case where static constructors in generic types are relied on to run once for each closed generic type is classes like EqualityComparer<T>, where the static constructor can be used to initialize the Default property once for each type T.

like image 37
Sam Harwell Avatar answered Apr 02 '23 10:04

Sam Harwell