Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

REFLECTION with STATIC in C#

The following program explains the usage of reflection principle with static.

Example:
  1. using System;
  2. using System.Reflection;
  3.  
  4. namespace forgetCode
  5. {
  6.  
  7. class Chennai
  8. {
  9. static Chennai()
  10. {
  11. Console.WriteLine("Chennai loaded");
  12. }
  13. }
  14.  
  15.  
  16. class Delhi
  17. {
  18. static Delhi()
  19. {
  20. Console.WriteLine("Delhi loaded");
  21. }
  22.  
  23. public static string special = "Capital city";
  24. }
  25. class Mumbai
  26. {
  27. static Mumbai()
  28. {
  29. Console.WriteLine("Mumbai loaded");
  30. }
  31. }
  32.  
  33. public class SweetShop
  34. {
  35. public static void Main()
  36. {
  37. Console.WriteLine("Inside Main");
  38. new Chennai();
  39. Console.WriteLine("After creating Chennai");
  40. Type t = Type.GetType("Delhi");
  41. Console.WriteLine("After Type.GetType(\"Delhi\")");
  42. Console.WriteLine(Delhi.special);
  43. Console.WriteLine("Before creating Mumbai");
  44. new Mumbai();
  45. Console.WriteLine("After creating Mumbai");
  46. }
  47. }
  48.  
  49. }

Output:
Inside Main
Chennai loaded
After creating Chennai
After Type.GetType("Delhi")
Delhi loaded
Capital city
Before creating Mumbai
Mumbai loaded
After creating Mumbai

You can see that each Class object is loaded only when it’s needed, and the static constructor is run immediately prior to when data from the Type is needed (in this case, the static string that told the Delhi's special).
This is in slight contrast to Java, which instantiates the static state of a type immediately upon class loading.