Junior — Middle
Can you explain what is meant by reflection in programming?
sobes.tech AI
Answer from AI
Reflection in programming is the ability of a program to examine and modify its structure and behavior at runtime. In C#, reflection allows obtaining information about types, methods, properties, and attributes of objects during program execution.
Example of using reflection in C#:
using System;
using System.Reflection;
class Program
{
static void Main()
{
Type type = typeof(String);
Console.WriteLine("Methods of the String class:");
MethodInfo[] methods = type.GetMethods();
foreach (var method in methods)
{
Console.WriteLine(method.Name);
}
}
}
This code outputs a list of all methods of the String class. Reflection is useful for dynamically invoking methods, creating objects, and analyzing types without knowing them at compile time.