Bassam Alugili
Bassam Alugili

Reputation: 16993

Static constructor called more than once

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 call This is the breakpoint for the second call

Upvotes: 5

Views: 3634

Answers (2)

Adam Houldsworth
Adam Houldsworth

Reputation: 64467

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.

Upvotes: 7

Sam Harwell
Sam Harwell

Reputation: 99859

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.

Upvotes: 2

Related Questions