HeadlinesBriefing favicon HeadlinesBriefing.com

C# Dynamic Leaks: A Dapper Trap

DEV Community •
×

The `dynamic` keyword in C# offers flexibility at system boundaries, but it creates hidden dangers. It bypasses compile-time checks, allowing type safety to erode silently within your code. Method signatures can appear perfectly safe while runtime conversions happen underneath, leading to performance issues and potential runtime errors that static typing aims to prevent.

Author DimonSmart created the DynamicLeakAnalyzer after encountering these issues in real projects. This Roslyn analyzer detects two critical rules: DSM001 for implicit dynamic conversions and DSM002 for `var` declarations that become dynamic. The tool specifically targets Dapper users, where non-generic `QueryFirst()` calls return `dynamic` rows, masking the true type of data being accessed.

Fixing these leaks requires discipline at the code boundary. Developers should prefer strongly-typed Dapper APIs like `QuerySingle<int>()` or map results to specific DTOs. If a dynamic row is unavoidable, cast it immediately to a static type. The analyzer can be installed via NuGet and configured in `.editorconfig` to treat warnings as errors, enforcing type safety.