In C#, how does a CLI tool find every ICommand class in its assembly and create each with Activator.CreateInstance, and what can fail?
answer
- enumerate, filter, create
- assignable is not constructible
- interfaces and abstract bases slip through
- parameterless constructor or exception
- constructor exceptions arrive wrapped
basics
~10 sScan Assembly.GetTypes(), keep classes that are non-abstract and assignable to ICommand, then call Activator.CreateInstance(type). A missing parameterless constructor throws MissingMethodException; a constructor that throws arrives as TargetInvocationException.
solid answer
~30 sTake `typeof(ICommand).Assembly.GetTypes()`, keep types where `typeof(ICommand).IsAssignableFrom(t)` and `t.IsClass && !t.IsAbstract` (the interface itself and abstract bases are assignable but not constructible), and create each with `Activator.CreateInstance(t)`. Without a public parameterless constructor you get `MissingMethodException`; an exception thrown inside the constructor comes back as `TargetInvocationException` with the original in `InnerException`. The `CreateInstance(Type, params object?[]?)` overload picks a constructor by its arguments at run time, so mismatches surface only when that command is created. Where the type is known at compile time, `where T : new()` moves the constructor check into the build.
code
csharp · 30 lines#:property PublishAot=false
using System.Reflection;
var commandTypes = typeof(ICommand).Assembly.GetTypes()
.Where(t => typeof(ICommand).IsAssignableFrom(t) && t is { IsClass: true, IsAbstract: false })
.OrderBy(t => t.Name);
foreach (Type t in commandTypes)
{
try
{
var cmd = (ICommand)Activator.CreateInstance(t)!;
Console.WriteLine($"{cmd.Verb} -> {t.Name}");
}
catch (MissingMethodException e) { Console.WriteLine($"{t.Name}: {e.Message}"); }
catch (TargetInvocationException e) { Console.WriteLine($"{t.Name}: wrapped {e.InnerException!.GetType().Name}"); }
}
var push = (ICommand)Activator.CreateInstance(typeof(PushCommand), "origin")!;
Console.WriteLine(push.Verb);
interface ICommand { string Verb { get; } }
abstract class CommandBase : ICommand { public abstract string Verb { get; } }
class DeployCommand : CommandBase { public override string Verb => "deploy"; }
class StatusCommand : ICommand { public string Verb => "status"; }
class PushCommand(string remote) : ICommand { public string Verb => $"push {remote}"; }
class FailingCommand : ICommand
{
public FailingCommand() => throw new InvalidOperationException("no config");
public string Verb => "fail";
}go deeper
Know that Activator.CreateInstance builds an object from a Type and needs a public parameterless constructor unless you pass arguments.
Explain the scan, why IsAssignableFrom needs the IsClass and IsAbstract checks, and what MissingMethodException and TargetInvocationException mean here.
Discuss doing discovery once at startup, creating only the requested command, handling ReflectionTypeLoadException, and why trimming warns about the whole loop.
Weigh discovery by reflection against explicit registration or a generator: convenience for contributors versus failures that move from build time to a user's first run.
## The discovery loop A command-line tool with one class per verb (`deploy`, `status`, `push`) can avoid a hand-maintained list by asking its own assembly which classes implement `ICommand` and creating one of each. Three reflection steps do it. 1. **Enumerate types.** `typeof(ICommand).Assembly` is the assembly that declares the interface; `Assembly.GetTypes()` returns every type defined in it, public and internal. 2. **Filter.** `typeof(ICommand).IsAssignableFrom(t)` is true when a value of type `t` can be stored in an `ICommand` variable. 3. **Create.** `Activator.CreateInstance(t)` calls `t`'s public parameterless constructor and returns the new object as `object`, which you cast to `ICommand`. ## The filter must exclude what cannot be constructed `IsAssignableFrom` answers "is this type compatible with `ICommand`?", which is not the same as "can I create one?". - It returns **true for `ICommand` itself**: an interface is assignable to itself. - It returns **true for an abstract base** such as `CommandBase`. - `Activator.CreateInstance` on either throws `MissingMethodException`, with the reasons "Cannot create an instance of an interface." and "Cannot create an abstract class." respectively. So the filter adds `t.IsClass && !t.IsAbstract` (in the snippet, the property pattern `t is { IsClass: true, IsAbstract: false }`). Structs that implement the interface are not a problem for `Activator`, which can create value types, but a command registry built from classes usually leaves them out on purpose. ## What `Activator.CreateInstance` can throw | Situation | What you get | |---|---| | No public parameterless constructor (`class PushCommand(string remote)`) | `MissingMethodException`: "Cannot dynamically create an instance of type 'PushCommand'. Reason: No parameterless constructor defined." | | Arguments that match no public constructor (`CreateInstance(typeof(PushCommand), 42)`) | `MissingMethodException` | | The constructor runs and throws | `TargetInvocationException`, with the constructor's exception in `InnerException` | | An interface or abstract class | `MissingMethodException` | The overload `Activator.CreateInstance(Type, params object?[]? args)` chooses a public constructor whose parameters fit the arguments, which is how the snippet creates `PushCommand` with `"origin"`. The match happens at run time, so a constructor whose parameter types change still compiles and fails only when that verb is first created. The wrapping in the third row matters for error messages: a tool that catches `InvalidOperationException` around `CreateInstance` never sees it, because it arrives wrapped. ## Activator vs a `new()` constraint When the type is known at compile time, generics do the same job with checking up front: ```csharp static T Create<T>() where T : ICommand, new() => new T(); ``` The compiler refuses `Create<PushCommand>()` because `PushCommand` has no parameterless constructor, so the error moves from the user's first `push` to the build. `Activator` is the tool for types you only learn about at run time, as in a discovery scan. The constraint rules themselves are covered with generic constraints. ## Operational details a reviewer will ask about - **Discovery cost and order.** `GetTypes()` materialises a `Type` object for every type in the assembly, so run the scan once at startup and keep a `Dictionary<string, Type>` keyed by verb. Sort the result if help output must be stable; the snippet uses `OrderBy`. - **What `GetTypes()` returns.** It includes internal types and compiler-generated ones, such as the `<>c` class that holds a file's lambdas, not only public classes. `Assembly.GetExportedTypes()` returns only the publicly visible types, which is the narrower choice when a plugin contract must be public. - **`ReflectionTypeLoadException`.** `Assembly.GetTypes()` throws it when one or more types cannot be loaded, typically because a dependency is missing. Its `Types` property holds the types that did load and `null` for the rest, and `LoaderExceptions` explains each failure. - **Instances per run.** Creating every command eagerly runs every constructor, including ones that read configuration or open files. A registry of `Type` objects, with `Activator.CreateInstance` only for the verb the user typed, keeps a broken command from stopping the others. - **Trimming and Native AOT.** `Assembly.GetTypes()` is marked `[RequiresUnreferencedCode]`, and `Activator.CreateInstance(Type)` annotates its parameter with `[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]`, a requirement a `Type` from a scan cannot meet. A published, trimmed tool gets analysis warnings for this loop. The fixes (explicit registration with an annotated generic method, or a source generator) are covered with the trimming warnings.
- Each command needs a `Handler<T>` where `T` is the command type found by the scan. How do you create one?Build the closed type at run time with `typeof(Handler<>).MakeGenericType(commandType)` and pass it to `Activator.CreateInstance`. `GetGenericArguments()` and `GetGenericTypeDefinition()` take such a type apart again. `MakeGenericType` throws `ArgumentException` when the type argument breaks a constraint, and under Native AOT it raises IL3050, because that instantiation's native code may not exist.
- Why might the scan fail with `ReflectionTypeLoadException` on one machine but not another?`Assembly.GetTypes()` must load every type in the assembly, and a type whose base class or interface lives in a missing or mismatched dependency cannot load. The exception's `Types` array holds the loaded types with `null` for the failures, and `LoaderExceptions` says why each one failed. A scan should log those, not crash the tool.
- IsAssignableFrom already excludes interfaces and abstract classes
- Activator.CreateInstance can call a constructor that takes parameters with no arguments supplied
- A constructor's exception reaches the caller unwrapped
- Activator.CreateInstance cannot create instances of struct types
- A missing parameterless constructor is reported at compile time