Updated on
The dynamic type in C# turns off compile-time type checks for a variable. The compiler lets any method call or operator through, and the runtime checks it against the real type of the value when the line runs.
It arrived in C# 4.0, with Visual Studio 2010, to bypass the static type checks and add more flexibility to the language. Let’s see how it works and how it compares to reflection, var and object.
Let’s start.
What Does the dynamic Keyword Do in C#?
C# is a statically typed language, so what is dynamic doing in it? The dynamic keyword tells the compiler to stop checking types for one variable, field, parameter or return value. Microsoft Learn puts it this way: “The dynamic type is a static type, but an object of type dynamic bypasses static type checking.”
We can assign anything to a dynamic variable and call any method or operator on it. The compiler accepts the code and stores a description of each call. When the line runs, the runtime binder looks at the actual type of the value and binds the call to it.
If the call makes sense for that type, it runs. If it doesn’t, we get a RuntimeBinderException where we would otherwise have had a compiler error.
There’s no new type at run time either. The compiler emits dynamic as plain object plus a marker attribute, and the value keeps its own type. Only the type check moves, from compile time to run time.
The dynamic type has been added to C# since version 4 because of the need to improve interoperability with COM (Component Object Model) and other dynamic languages. While that can be achieved with reflection, the dynamic type provides a natural and more intuitive way to implement the same code.
We declare a dynamic variable with the dynamic keyword, and we can assign it a value of any other type.
Here is an example of two dynamic variables, one that is instantiated as an int, and another that is a complex type (Book).
dynamic intNumber = 12; dynamic book = new Book(isbn);
Book is a small record from our sample project, and isbn is a string. The later examples use the sample’s Employee, WorkStatus and EmployeeFactory types and its GetEmployeeFactory() helper in the same way.
Simple enough.
How Does C# Bind a dynamic Variable at Run Time?
Essentially, when you declare a variable dynamic, you are telling the compiler to turn off the compile-time type checks. Dynamic is basically System.Object type under the hood, but it doesn’t need to explicitly cast a value before using it. More on that a bit later in the article.
For now, let’s see how dynamic type works on some examples.
We can start by creating a dynamic variable:
dynamic testVariable = 5; Console.WriteLine(testVariable.GetType());
Can you guess the output of the Console.WriteLine()? It’s not hard to guess: it is of course System.Int32.
So what happens if we change the value of the testVariable to something entirely different like “Hello World”:
testVariable = "Hello World"; Console.WriteLine(testVariable.GetType());
Now we get the output System.String.
But if we wish to do something like incrementing a value now, we’ll get an exception:
Console.WriteLine(testVariable++);
The code will compile, but we are going to get an exception when we run the application:
Our sample’s Program.cs catches the exception and prints its type and message, so the whole example prints:
System.Int32 System.String Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Operator '++' cannot be applied to operand of type 'string'
RuntimeBinderException is the exception you will probably see the most when you work with dynamic type. As the exception message states, we cannot use the ++ operator on the variable of the type string. So that means that the dynamic type behaves like the last type we’ve assigned to it.
One more example to wrap it up.
We have a class that gets us the instance of some logger implementation:
dynamic logger = LoggerFactory.GetLogger();
logger.LogInfo("Hi");
logger.LogWarning("You are about to enter a time warp");
logger.LogError("System is malfunctioning");
logger.LogTrace("Communication lost");
public class Logger
{
public void LogInfo(string message)
{
Console.WriteLine($"INFO: {message}");
}
public void LogWarning(string message)
{
Console.WriteLine($"WARNING: {message}");
}
public void LogError(string message)
{
Console.WriteLine($"ERROR: {message}");
}
}
public class LoggerFactory
{
public static Logger GetLogger()
{
return new Logger();
}
}
As far as the compiler is concerned, everything is fine. But once again we get the RuntimeBinderException because LogTrace method is not defined.
Here’s what our sample prints:
INFO: Hi WARNING: You are about to enter a time warp ERROR: System is malfunctioning Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'DynamicTypeInCSharp.Models.Logger' does not contain a definition for 'LogTrace'
Okay, so that’s how the dynamic type in C# works. But what are some common use cases for dynamic type?
Should We Use the Dynamic Type in C#?
First of all, let’s make it clear that dynamic is not a silver bullet. We shouldn’t use it just because we can.
While it has its benefits, dynamic objects are harder to work with while writing code, since we don’t have an IntelliSense for them due to the nature of dynamic type. On the other hand, if we have a need to implement dynamic type everywhere, we are probably using the wrong type of language. Dynamic languages are better suited for those kinds of cases.
So what are the common cases to apply a dynamic type to:
- Communicating with other dynamic languages
- Simplifying responses from API calls when we don’t know what type of object to expect (or we don’t care), for example when we deserialize JSON into a dynamic object
- Creating libraries that can be used between languages
- Making generic solutions when speed isn’t the main concern
- Replacing and simplifying reflection code
- More?
So why shouldn’t we use dynamic all the time? Because:
- It’s slower than statically typed code. In our benchmark, a dynamic method call took about 9 nanoseconds, while the same static call took well under one nanosecond
- Increases the chance to get runtime exceptions
- Decreases code readability in some cases, and working with it is a bit harder due to the lack of IntelliSense
Ok, so let’s see some concrete examples of dynamic in action.
Dynamic vs Reflection
Reflection is a mechanism to get the type of a System.Object object, and to invoke its members without knowing what the concrete type of that object is.
For example, let’s see what a typical reflection flow looks like:
using System.Reflection;
EmployeeFactory employeeFactory = GetEmployeeFactory();
object firstEmployee = employeeFactory.GetFirstEmployee();
Type firstEmployeeType = firstEmployee.GetType();
object? workStatusObject = firstEmployeeType.InvokeMember("GetWorkStatus",
BindingFlags.InvokeMethod, null, firstEmployee, null);
var workStatus = (WorkStatus)workStatusObject!;
Console.WriteLine(workStatus);
This piece of code although very complicated and large for its purpose retrieves an employee’s work status. All that code just to call one method.
That’s because our EmployeeFactory class returns an employee as a generic System.Object type. System.Object is the base class of all other classes and we can always use it when we don’t know what type of object to expect.
To call the method of an object of the type System.Object we need to find out what type of object it is. We do that by calling the object.GetType() method. After that, we can use the InvokeMember() method to explicitly call GetWorkStatus method, on the firstEmployee object.
InvokeMember() hands the result back as an object?, so we cast it to WorkStatus before we can finally find out the work status of the firstEmployee.
Now let’s see what the same example looks like by using dynamic:
EmployeeFactory employeeFactory = GetEmployeeFactory(); dynamic firstEmployee = employeeFactory.GetFirstEmployee(); WorkStatus workStatus = firstEmployee.GetWorkStatus(); Console.WriteLine(workStatus);
Well, that looks much simpler and easier to read. Moreover, we didn’t have to think about types or type method names as strings.
So, in the battle of dynamic vs reflection we get:
- Cleaner and more readable code
- Better performance, because the runtime caches how each dynamic call was bound and reuses it on the next call
- Not having hardcoded strings in our code
- Easier implementation
Once again, a small disclaimer. This example is for demonstration purposes only. Generally, both dynamic and reflection should be used sparingly and not just “because we can”.
Both dynamic and reflection cost far more per call than a static call, and introduce bugs we could have avoided by implementing static mechanisms and abstractions correctly.
How Much Slower Is a dynamic Call?
Let’s put numbers on that. Our sample has a small BenchmarkDotNet class that reads the same employee’s work status three ways: a static call, a dynamic call and a reflection call:
using System.Reflection;
using BenchmarkDotNet.Attributes;
[InProcess]
[MemoryDiagnoser]
public class MethodCallBenchmarks
{
private readonly Employee _employee = new() { Id = "1", Name = "Johnny Depp" };
private readonly object _employeeObject;
private readonly dynamic _employeeDynamic;
public MethodCallBenchmarks()
{
_employeeObject = _employee;
_employeeDynamic = _employee;
}
[Benchmark]
public WorkStatus StaticCall() => _employee.GetWorkStatus();
[Benchmark]
public WorkStatus DynamicCall() => _employeeDynamic.GetWorkStatus();
[Benchmark]
public WorkStatus ReflectionCall() =>
(WorkStatus)_employeeObject.GetType().InvokeMember("GetWorkStatus",
BindingFlags.InvokeMethod, null, _employeeObject, null)!;
}
All three fields point at the same Employee, so the only thing that changes is how we call the method. Here are the results:
| Method | Mean | Error | StdDev | Gen0 | Allocated | |--------------- |-----------:|----------:|----------:|-------:|----------:| | StaticCall | 0.0043 ns | 0.0034 ns | 0.0032 ns | - | - | | DynamicCall | 9.0709 ns | 0.1796 ns | 0.3098 ns | 0.0029 | 24 B | | ReflectionCall | 73.1079 ns | 1.3561 ns | 1.2021 ns | 0.0095 | 80 B |
The static call is so cheap that BenchmarkDotNet can’t tell it apart from an empty method. The dynamic call costs about 9 nanoseconds and allocates 24 bytes per call. The reflection call is about eight times slower than the dynamic one and allocates 80 bytes.
The dynamic call stays that cheap because of the caching from the bullet list above: after the first call, the call site reuses the binding it worked out.
A few nanoseconds won’t matter for a call we make a few times per request. In a loop that runs millions of times, they add up, and that’s where a static type or an interface pays off.
What Is the Difference Between var, object and dynamic?
All three let us write a variable without spelling out its exact type, but they work at different times.
var is the compiler’s job. It infers the type from the value we assign, and from then on the variable is as strongly typed as if we had written the type ourselves. The type can’t change later.
object is the base type of every other type in C#. We can store anything in it, but to use the value as what it really is, we have to cast it first. A wrong cast compiles fine and fails at run time with an InvalidCastException.
dynamic is object with the compile-time checks switched off. We can store anything and call anything on it without a cast. The runtime binds each call when the line runs, which costs time on every call and turns a typo into a RuntimeBinderException.
If we know the type when we write the code, var or the type name is the right choice.
Let’s break them down.
Var Keyword
Var is used in a method scope to implicitly type a variable. The variable is still strongly typed, and the compiler decides its type at compile time, from the value we assign. We can even see the type by hovering over the var keyword.
var imNumber = 10; //implicitly typed variable int exNumber = 10; //explicitly typed variable
Our opinion is that var improves the readability of the code and it should be used because more often than not we don’t need to explicitly type our variables.
Especially if the types are complicated.
For example Dictionary<string, IEnumerable<Employee>> or something even more complicated. The type of the variable cannot be changed at runtime.
There are pros and cons to using var, but that’s beyond the scope of this article. If you are interested in learning more about when to use it and when not, check out this blog post: When to Use and Not Use var in C#.
Object Keyword
The object is an alias for System.Object which is the ultimate base class in C#. Every class in C# is derived from System.Object, and we can utilize that fact to make a more generic codebase. Through the object type, we can get the concrete type of the object we are working with, in runtime. While we can achieve pretty much anything in terms of abstraction with System.Object, sometimes we are forced to use reflection to achieve the goal we want, which is not ideal. Most of the time, a cast is enough.
To be able to use the type that is assigned to the System.Object variable, we need to explicitly cast it first. For example:
object testObj = 10; testObj = (int)testObj + 10;
Dynamic Keyword
Dynamic is actually an object type but it bypasses compiler type checks. We can assign anything to a dynamic variable and not worry about the compiler or the type. It utilizes the power of DLR which is an extension of CLR.
Although bypassing compiler checks is nice, it could potentially lead to unexpected behavior if not used carefully. We don’t need to explicitly cast dynamic before trying out different operations.
dynamic testDynamic = 10; testDynamic = testDynamic + 25;
We didn’t need a cast and the compiler doesn’t complain, but a wrong operation here would only show up when the line runs. Here’s how the three compare side by side:
var | object | dynamic |
|
|---|---|---|---|
| The type is fixed | at compile time, from the value we assign | at compile time, as object | at compile time as dynamic, and each call binds at run time |
| Compile-time checks | yes | yes, against object members only | no |
| Cast needed to use the value | no | yes | no |
| A mistake shows up as | a compiler error | an InvalidCastException at run time | a RuntimeBinderException at run time |
| Where we can use it | local variables | almost anywhere a type goes | almost anywhere a type goes |
Why Do We Get a RuntimeBinderException?
RuntimeBinderException is the exception we get at execution time if a dynamic type fails to resolve the operation we provided on a type that doesn’t support it.
To put it in simple terms, imagine you are trying to do something on a static type and that static type doesn’t implement that behavior.
Like trying to increment a string. Or calling the String.Split() on an integer.
It’s not that simple though, there are some gotchas that we should be aware of. For example, reading the Count property on a dynamic object that has been assigned an ICollection, in a method of our static Examples class:
using System.Collections;
public static void ExamplePrintCount(ICollection collection)
{
dynamic dynamicCollection = collection;
Console.WriteLine("Static typing: {0}", collection.Count);
Console.WriteLine("Dynamic typing: {0}", dynamicCollection.Count);
}
If we run this example by providing an int array:
Examples.ExamplePrintCount(new int[20]);
What do you think the result will be?
If you guessed that first Console.WriteLine() will output 20, and that we’ll get RuntimeBinderException in the second one, you guessed it right. Here’s what our sample prints:
Static typing: 20 Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'System.Array' does not contain a definition for 'Count'
Why does the static call work and the dynamic one fail? Arrays implement ICollection.Count explicitly, so Count exists only when we look at the array through the interface. The runtime binder ignores the fact that the value came in as an ICollection. It binds against the value’s real type, an array, and an array has no public Count.
This example comes from the C# in Depth book, and its author wrote it up in Gotchas in dynamic typing. We recommend you read that article if you are serious about using dynamic in your applications. It will definitely save you some time, reduce headaches and prolong your lifespan.
Conclusion
The dynamic type is a useful construct. It has a variety of usages and it can both help us or make our life tougher if we are not careful when and how we implement it.
While dynamic has originated from the need of overcoming interoperability problems, there are a lot of nice examples you can find today where dynamic type is utilized in the best possible way. Take for example DalSoft.RestClient we’ve already written about. It is a full-blown dynamic library for consuming restful APIs from C#.
This is not all that the dynamic feature can do for us. ExpandoObject lets us add and remove members at run time, and DynamicObject is a base class for types that decide their own dynamic behavior. We compare all three in our article on the differences between ExpandoObject, DynamicObject and dynamic.
Tested with .NET 11.0.0 and BenchmarkDotNet 0.15.8.

Does .Net core fully support the DLR (call-site caching in dynamics, etc.), or only the full framework?