Introducing Radical.sh

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

Type retrieval operator in C#

C# provides a way to produce the reference to the Type object, using the type retrieval operator typeof( ).

It would look like:
  1. typeof(classname);


It will be safer since it’s checked at compile-time.
Because it eliminates the method call, it’s also more efficient.

Example:
  1. using System;
  2. using System.Reflection;
  3.  
  4. namespace forgetCode
  5. {
  6. static class ReflectionTest
  7. {
  8. public static int Length;
  9. public static void Write()
  10. {
  11. //C# checks this at compile time itself
  12.  
  13. Type type = typeof(ReflectionTest); // Get type pointer
  14.  
  15. FieldInfo[] fields = type.GetFields(); // Obtain all fields
  16. foreach (var field in fields) // Loop through fields
  17. {
  18. string name = field.Name; // Get string name
  19.  
  20. object temp = field.GetValue(null); // Get value
  21. if (temp is int) // See if it is an integer.
  22. {
  23. int value = (int)temp;
  24. Console.Write(name);
  25. Console.Write(" (int) = ");
  26. Console.WriteLine(value);
  27. }
  28. }
  29. }
  30. }
  31.  
  32. class Program
  33. {
  34. static void Main()
  35. {
  36. ReflectionTest.Length = 100; // Set value
  37. ReflectionTest.Write(); // Invoke reflection methods
  38. }
  39. }
  40.  
  41. }