Reflection lets a program look at and change its own parts while running. This can skip the usual checks done before running, called compile-time safety.
How reflection bypasses compile-time safety in C Sharp (C#)
Type type = typeof(SomeClass); MethodInfo method = type.GetMethod("MethodName"); object instance = Activator.CreateInstance(type); method.Invoke(instance, new object[] { parameters });
Reflection uses types like Type, MethodInfo, and PropertyInfo to inspect and invoke code.
Because it works at runtime, it can bypass compile-time checks like type safety and access modifiers.
ToUpper method on a string using reflection.Type type = typeof(string); MethodInfo method = type.GetMethod("ToUpper", Type.EmptyTypes); string text = "hello"; string result = (string)method.Invoke(text, null); Console.WriteLine(result);
Now property of DateTime using reflection.Type type = Type.GetType("System.DateTime"); object now = type.GetProperty("Now").GetValue(null); Console.WriteLine(now);
using System; using System.Reflection; class Person { private string secret = "hidden"; } Person p = new Person(); var field = typeof(Person).GetField("secret", BindingFlags.NonPublic | BindingFlags.Instance); string secretValue = (string)field.GetValue(p); Console.WriteLine(secretValue);
This program uses reflection to call the ToLower method on a string. It bypasses compile-time checks by invoking the method at runtime.
using System; using System.Reflection; class Program { static void Main() { Type type = typeof(string); MethodInfo method = type.GetMethod("ToLower", Type.EmptyTypes); string text = "HELLO WORLD"; string result = (string)method.Invoke(text, null); Console.WriteLine(result); } }
Reflection can cause errors at runtime if method names or types are wrong, since compile-time checks are skipped.
Using reflection can slow down your program because it does extra work at runtime.
Reflection can access private members, so use it carefully to avoid breaking encapsulation.
Reflection lets programs inspect and change themselves while running.
It bypasses compile-time safety checks like type checking and access control.
This is useful for dynamic behavior but should be used carefully to avoid errors and performance issues.