6 comments on “Static in generics

  1. It might be more interesting to compare Derived1 and Derived2 instead of two instances of Derived2. It’s not that surprising that the static constructor is run only once in that case.

    It’s worth pointing out that this feature of the language/runtime can be put to good use. If you want to create a static cache of objects of any type indexed by a string, you can have an ObjectCache type that has a static Dictionary. Then you will be creating a new Dictionary object for each T that is used at runtime.

    Also, note that in Java this is not the case due to type erasure. Since generic types do not exist at runtime (they are purely a compile-time construct) static members on generic classes are only initialized once, and there is really only once instance of them.

    • It might be more interesting to compare Derived1 and Derived2 instead of two instances of Derived2. It’s not that surprising that the static constructor is run only once in that case.
      Are you talking about this code below?

       public class Base < T  
      {
              public static string str;
      
              static Base()
              {
                  str = "hello";
                  System.Console.WriteLine("Static ctor cald");
              }
          }
      
          class Derived1 < T : Base  T
          { }
      
          class Derived2 < T : Base  < T
          { }
      
         class Program 
          {
              public static void Main(string[] args)
              {
                  Derived1 <int der = new Derived1<int ();
                  Derived2 <int der1 = new Derived2<int ();
      
                  Console.ReadKey();
              }     
      

      If so, i thought this code might create a lil confusion. Hence i did showed the other one. But yes this also a good example. Thanks :)

      It’s worth pointing out that this feature of the language/runtime can be put to good use. If you want to create a static cache of objects of any type indexed by a string, you can have an ObjectCache type that has a static Dictionary. Then you will be creating a new Dictionary object for each T that is used at runtime.

      Btw, would you mind showing an real world example where this design challenge is put into effect? Perhaps a code plz?

      Note: In the code above, the closing angle braces are purposefully left because of wordpess issues.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s