Skip to content

1.22 — Anonymous Types, dynamic, and var

← Roadmap · Section: 1. C# Language Fundamentals Prev: 1.21 IDisposable · Next: 1.23 Attributes and reflection

Markers: — · Confidence: 🔴 · Last reviewed: —


TL;DR

  • var is still fully type-safe. The compiler works out the type and fixes it. var x = 5; and int x = 5; produce identical code.
  • dynamic genuinely turns off type checking until runtime. Everything becomes a runtime error waiting to happen.
  • Anonymous types (new { Name = "Ada" }) are real, compiler-generated classes. Useful inside a method, useless outside one.

The concept

These three get grouped together because they all look like "the type is not specified". Only one of them actually is.

  • var — "compiler, work out the type for me". Type safety is completely intact.
  • dynamic — "do not check anything, sort it out at runtime". Type safety is gone.
  • anonymous type — "make me a throwaway class here and now".

The interview question is almost always var versus dynamic. The answer is that they are not remotely similar, and confusing them is a red flag.


How it works

var — type inference

The compiler looks at the right-hand side and works out the type. Once it has, that type is fixed forever.

var number = 5;              // compiler decides: int
var name = "Ada";            // compiler decides: string
var list = new List<Order>();// compiler decides: List<Order>

number = "hello";            // COMPILE ERROR — number is an int, permanently

var x = 5; and int x = 5; compile to exactly the same IL. There is no runtime cost and no loss of safety. var is purely about how much you type.

Rules:

  • Only for local variables. Not for fields, parameters, or return types.
  • You must initialise it in the same statement — the compiler needs something to infer from.
  • Cannot be null on its own: var x = null; fails, because null does not identify a type.

When to use it is a style question, and teams differ. A reasonable position:

var order = new Order();                       // obvious — the type is right there
var orders = new List<Dictionary<string, int>>();  // obvious, and saves a lot of typing

var result = ProcessThings();                  // NOT obvious — what does this return?
IReadOnlyList<Order> result = ProcessThings(); // clearer

The test: can a reader tell the type from this one line? If yes, var is fine. If they would have to go and look at the method signature, write the type out.

dynamic — no compile-time checking at all

dynamic value = GetSomething();
value.AnyMethodAtAll();          // compiles fine, whatever it is
value.ThisDoesNotExist();        // ALSO compiles fine
                                 // → RuntimeBinderException when it runs

The compiler stops checking entirely. Member lookup happens while the program is running, using the Dynamic Language Runtime.

The costs are real:

  • No compile-time errors. Every typo becomes a runtime crash.
  • No IntelliSense. Your editor cannot help you.
  • Slower. Every call goes through a lookup and caching mechanism.
  • No refactoring safety. Rename a property and dynamic call sites are silently missed.

When is it justified? Genuinely rarely:

  • Talking to COM objects, like Office automation
  • Interoperating with a dynamic language such as IronPython
  • Truly unknown JSON shapes — though JsonNode or JsonElement is usually better

If you find yourself reaching for dynamic in normal application code, there is almost always a better answer: an interface, a generic, or pattern matching.

dynamic vs object vs var

This comparison is a common question:

object o = "hello";
o.Length;              // COMPILE ERROR — object has no Length. Cast first.

dynamic d = "hello";
d.Length;              // Compiles. Works at runtime. Returns 5.
d.Nonsense();          // Compiles. Throws at runtime.

var v = "hello";
v.Length;              // Compiles. v IS a string — full IntelliSense.
v.Nonsense();          // COMPILE ERROR — caught immediately.
Checked at compile time? Needs a cast? IntelliSense?
var Yes No Yes
object Yes Yes No, until cast
dynamic No No No

Anonymous types

var person = new { Name = "Ada", Age = 36 };
Console.WriteLine(person.Name);      // fully typed, IntelliSense works

The compiler generates a real class behind the scenes with read-only properties, a value-based Equals and GetHashCode, and a helpful ToString.

Their limitation is that the type has no name you can write. So you cannot return one from a method, put one in a field, or use it as a parameter type. It only works inside the method that created it — which is exactly why var is required for them.

Their main real use is LINQ projections:

var summary = orders
    .Where(o => o.Total > 100)
    .Select(o => new { o.Id, o.CustomerName, o.Total })   // only these 3 columns
    .ToList();

In Entity Framework this is genuinely useful, because it means the generated SQL only selects the three columns you actually need instead of the whole row. See 13.15.

But once the data leaves the method, use a record instead:

public record OrderSummary(Guid Id, string CustomerName, decimal Total);

public IReadOnlyList<OrderSummary> GetSummaries() =>
    _db.Orders
       .Where(o => o.Total > 100)
       .Select(o => new OrderSummary(o.Id, o.Customer.Name, o.Total))
       .ToList();

Same SQL benefit, but now it has a name, it can be returned, and it appears properly in Swagger.


Interview questions

Q: What is the difference between var and dynamic?

They are completely different despite looking similar. var is compile-time type inference — the compiler works out the type from the initialiser and fixes it permanently, so you get full type checking, IntelliSense and no runtime cost at all. var x = 5; compiles to exactly the same thing as int x = 5;. dynamic switches type checking off entirely: member lookup is deferred to runtime, so any typo compiles fine and throws when it executes, there is no IntelliSense, and every call has overhead. var is about convenience; dynamic is about giving up safety, and it is rarely the right choice.

Q: When is dynamic actually appropriate?

When the type genuinely is not known until runtime and there is no reasonable alternative — COM interop like automating Excel, interoperating with a dynamic language, or handling completely unstructured data. Even for JSON, JsonNode or JsonElement is usually a better answer because it gives you a real API. In ordinary application code, reaching for dynamic is normally a sign that an interface or a generic would solve the problem properly.

Q: What is an anonymous type and where would you use one?

It is a compiler-generated class created inline with new { Name = "Ada" }. The compiler produces a real type with read-only properties and value-based equality, but that type has no name you can write, so it cannot leave the method it was created in. That makes them useful for LINQ projections — selecting only the three columns you need from a query so that Entity Framework generates narrower SQL. As soon as the data needs to cross a method boundary, a record is the better choice, because it has a name, it can be returned, and it shows up properly in API documentation.

Q: Does var have any runtime cost?

None at all. It is purely a compile-time convenience. The compiler determines the concrete type and emits exactly the same IL as if you had typed the type out yourself. The variable is just as strongly typed either way.


Traps ⚠️

  • Thinking var is weakly typed. It is not. The type is fixed at compile time.
  • dynamic turns every typo into a runtime crash. No compiler help, no IntelliSense, no safe refactoring.
  • Overusing var hurts readability. var result = Process(); tells a reader nothing.
  • Anonymous types cannot escape the method. No returning them, no fields, no parameters.
  • Anonymous type equality is by value, but only for the exact same shape. Two anonymous types with the same properties in a different order are different types.
  • dynamic silently defeats extension methods. Extension methods are resolved at compile time, so calling one on a dynamic fails at runtime.
  • var x = null; does not compile. You need string? x = null; or a cast.


Sources