wasAsked.

var vs dynamic

HCA Healthcare · Role not specified · technical

Published

Year not specified · C#

Community answers

Posted by wasAsked editorial collection

`var` is compile-time type inference. The variable still has one specific static type, and invalid member access is a compile error. `dynamic` postpones member binding until runtime; the compiler permits the call, but it can fail with `RuntimeBinderException`. Neither keyword means “no type.” ```csharp var customer = new Customer("Asha"); // statically Customer Console.WriteLine(customer.Name); // checked at compile time dynamic payload = GetLegacyComObject(); try { Console.WriteLine(payload.CustomerName); // resolved at runtime } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { logger.LogWarning(ex, "Unexpected legacy payload shape"); } ``` Prefer `var` when the assigned type is obvious and it improves readability, especially for anonymous types and LINQ projections. Use `dynamic` only at genuinely dynamic boundaries such as COM, some scripting systems, or legacy libraries. At JSON boundaries, typed DTOs or explicit `JsonElement` access are usually safer. `var value = GetDynamic()` still becomes dynamic if the expression's compile-time type is dynamic.

Prince Yadav · · 0 likes

Sign in to add your answer

Related interview topics