wasAsked.

Explain reflection

HCA Healthcare · Role not specified · technical

Published

Year not specified · C#

Community answers

Posted by wasAsked editorial collection

Reflection inspects metadata and interacts with types at runtime. It can discover assemblies, types, attributes, constructors, properties, and methods, and can create or invoke members dynamically. Frameworks use it for dependency registration, serialization, mapping, testing, and plugin discovery. ```csharp [AttributeUsage(AttributeTargets.Class)] public sealed class HandlerAttribute : Attribute { } [Handler] public sealed class PaymentHandler { public Task HandleAsync() => Task.CompletedTask; } var handlers = typeof(PaymentHandler).Assembly.GetTypes() .Where(type => type.GetCustomAttribute<HandlerAttribute>() is not null) .ToArray(); ``` Reflection trades compile-time guarantees and speed for flexibility. Repeated `GetProperty` or `MethodInfo.Invoke` calls in a hot path can allocate and be slower than direct calls; cache metadata or compile delegates when measurement justifies it. Handle `ReflectionTypeLoadException` during broad assembly scanning, avoid invoking untrusted types, and consider trimming or Native AOT: members reachable only through reflection may require annotations or source-generated alternatives.

Prince Yadav · · 0 likes

Reflection is the ability of a .NET program to inspect and use type metadata at runtime: discovering types, methods, properties, attributes and constructors, creating objects and invoking members without knowing them at compile time. It lives in the System.Reflection namespace. Basic examples: Type type = typeof(Customer); // or obj.GetType(), or Type.GetType("Namespace.Customer") foreach (PropertyInfo p in type.GetProperties()) Console.WriteLine($"{p.Name}: {p.PropertyType.Name}"); object instance = Activator.CreateInstance(type)!; type.GetProperty("Name")!.SetValue(instance, "Asha"); MethodInfo method = type.GetMethod("Greet")!; var message = method.Invoke(instance, ["Hello"]); // Reading custom attributes var required = type.GetProperty("Email")!.GetCustomAttribute<RequiredAttribute>() != null; // Loading types from assemblies (plugins) var plugins = Assembly.LoadFrom("Plugins.dll").GetTypes() .Where(t => typeof(IPlugin).IsAssignableFrom(t) && !t.IsAbstract); Where reflection is used - Frameworks: ASP.NET Core discovers controllers and model-binds parameters; EF Core maps entity properties; dependency injection containers read constructors; serializers (System.Text.Json, Newtonsoft) read properties; test frameworks find [Fact] or [Test] methods; AutoMapper maps properties. - Plugin systems, attribute-driven validation, generic admin screens, and tooling. Drawbacks - Performance: reflection calls are slower than direct calls and allocate more. Cache MethodInfo or PropertyInfo objects, or compile delegates with expression trees. - No compile-time safety: typos in member names fail at runtime. - Breaks encapsulation when used to access private members. - Trimming and Native AOT: code that reflects over types may break because the trimmer removes "unused" members. Annotations ([DynamicallyAccessedMembers]) help. Modern alternative: source generators produce code at compile time instead of reflecting at runtime — for example System.Text.Json source generation, the logging source generator ([LoggerMessage]) and regex source generators. They are faster and AOT-friendly. Summary: reflection is powerful for building frameworks and dynamic features, but in application code prefer strongly typed code, and cache or replace reflection on hot paths.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics