csharp / expert
Snippet
Dynamic Attribute-Based Method Discovery
This is a core pattern for building frameworks. By using reflection to scan for custom attributes, you can implement plugin systems or automated test runners that discover and execute logic dynamically at runtime.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
public void RunPlugins(object instance){var methods = instance.GetType().GetMethods().Where(m => m.GetCustomAttributes(typeof(PluginEntryPointAttribute), false).Any());foreach (var method in methods){method.Invoke(instance, null);}}
Breakdown
1
GetCustomAttributes(...)
Retrieves metadata markers applied to methods to identify specific behavior.
2
method.Invoke(instance, null)
Executes the discovered method dynamically, regardless of its name or hardcoded references.