Junior — Middle
Explain the concept of reflection in programming and its main applications.
sobes.tech AI
Answer from AI
Reflection in programming is the ability of a program to examine and modify its own structure and behavior at runtime. In C#, this is implemented through the namespace System.Reflection, which allows obtaining information about types, methods, properties, attributes, and creating objects dynamically.
Main uses of reflection:
- Dynamic creation of objects and invocation of methods without knowing them at compile time.
- Inspection of metadata for analyzing attributes and class structures.
- Serialization and deserialization of objects, when it is necessary to automatically traverse fields and properties.
- Development of frameworks and libraries that work with user-defined types (e.g., ORM, DI containers).
Example of using reflection to get a list of class methods:
using System;
using System.Reflection;
class Program
{
static void Main()
{
Type type = typeof(String);
MethodInfo[] methods = type.GetMethods();
foreach (var method in methods)
{
Console.WriteLine(method.Name);
}
}
}