Introducing Radical.sh

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

REFLECTION in C#

Reflection is the ability of a computer program to examine and modify the structure and behavior (specifically the fields, meta-data, properties and methods) of an object at runtime.

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 int Width;
  10. public static int Weight;
  11. public static string Name;
  12.  
  13. public static void Write()
  14. {
  15. Type type = typeof(ReflectionTest); // Get type pointer
  16. FieldInfo[] fields = type.GetFields(); // Obtain all fields
  17. foreach (var field in fields) // Loop through fields
  18. {
  19. string name = field.Name; // Get string name
  20.  
  21. object temp = field.GetValue(null); // Get value
  22. if (temp is int) // See if it is an integer.
  23. {
  24. int value = (int)temp;
  25. Console.Write(name);
  26. Console.Write(" (int) = ");
  27. Console.WriteLine(value);
  28. }
  29. else if (temp is string) // See if it is a string.
  30. {
  31. string value = temp as string;
  32. Console.Write(name);
  33. Console.Write(" (string) = ");
  34. Console.WriteLine(value);
  35. }
  36. }
  37. }
  38. }
  39.  
  40. class Program
  41. {
  42. static void Main()
  43. {
  44. ReflectionTest.Length = 100; // Set value
  45. ReflectionTest.Width = 50; // Set value
  46. ReflectionTest.Weight = 300; // Set value
  47. ReflectionTest.Name = "Forget Code"; // Set value
  48. ReflectionTest.Write(); // Invoke reflection methods
  49. }
  50. }
  51.  
  52. }

Output:
Length (int) = 100
Width (int) = 50
Weight (int) = 300
Name (string) = Forget Code