Skip to Content
Course content

95: Dynamic Type Usage with dynamic

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Wait, how is dynamic different from var? They both look like they're letting the compiler figure things out.

This is probably the most common point of confusion. Here is the short version: var is static; dynamic is not. When you use var, the compiler looks at the right side of the assignment, figures out the type, and then locks it in. Once it's set, it never changes. It's just a shortcut so you don't have to type Dictionary<string, List<int>> twice.

dynamic is a completely different animal. It tells the compiler: "Stop checking this. I don't care if this method or property exists right now. Just trust me, and figure it out when the code actually runs."

var name = "Alice"; 
// name = 10; // This would fail at compile time.

dynamic flexible = "Alice"; 
flexible = 10; // This is perfectly fine. The type changed at runtime.

I usually tell people to think of dynamic as a way to opt out of the C# type system for a specific variable.

If I can just use dynamic to avoid casting, why wouldn't I use it everywhere?

Because you're trading safety for convenience, and in a professional codebase, that's a dangerous trade. When you use dynamic, you lose IntelliSense. Your IDE can't tell you what methods are available because it literally doesn't know what the object is until the app is running. If you make a typo—say, calling .SaveData() instead of .Save()—the compiler won't blink. You'll just get a RuntimeBinderException and your app will crash in production.

There is also a performance hit. dynamic uses the Dynamic Language Runtime (DLR), which has to do a lot of heavy lifting behind the scenes to resolve members at runtime. It's slower than a standard method call. Use it as a scalpel, not a sledgehammer.

Where would I actually use this in a real project?

You won't use it often, but when you do, it's a lifesaver. The most common scenario I've encountered is dealing with COM APIs (like Excel or Word interop) or working with highly flexible JSON structures where the schema changes constantly.

Another great use case is ExpandoObject. This allows you to add properties to an object on the fly, which is almost impossible with standard C# classes. Look at this:

using System.Dynamic;

dynamic user = new ExpandoObject();
user.FirstName = "Jane";
user.LastName = "Doe";
user.Age = 30;

// I can add a new property whenever I want
user.LastLogin = DateTime.Now;

Console.WriteLine($"{user.FirstName} logged in at {user.LastLogin}");

If you tried to do that with a regular class, you'd have to define the properties in the class definition first. With dynamic and ExpandoObject, you're basically treating C# like JavaScript.

What happens if the dynamic object doesn't have the method I'm calling?

As I mentioned, it crashes. But specifically, it throws a Microsoft.CSharp.RuntimeBinder.RuntimeBinderException. Since you've bypassed the compiler's safety net, the responsibility is now on you to ensure the object is what you think it is. I always recommend wrapping dynamic calls in a try-catch block if you're dealing with data from an external source that you don't fully control.

try 
{
    dynamic data = GetExternalApiData();
    Console.WriteLine(data.UnexpectedProperty);
}
catch (Microsoft.CSharp.RuntimeBinderException ex)
{
    Console.WriteLine("The property didn't exist! " + ex.Message);
}



📋 Practical Task

Exercise: Building a Flexible User Profile Generator

You are building a system where user profiles can have an arbitrary number of attributes (some users have "TwitterHandle", others have "Company", others have "FavoriteColor"). Instead of creating a massive class with 100 nullable properties, you'll use ExpandoObject.

Your Task:

  • Create a method called CreateProfile(string name, Dictionary<string, object> attributes>).
  • Inside this method, initialize a dynamic object using new ExpandoObject().
  • Assign the name to a property called UserName on that dynamic object.
  • Loop through the attributes dictionary and dynamically add each key-value pair as a property to the object. (Hint: You'll need to cast the ExpandoObject to an IDictionary<string, object> to add properties via a loop).
  • In your Main method, call CreateProfile with a dictionary containing at least three different custom attributes.
  • Print out the UserName and one of the custom attributes directly from the resulting dynamic object to prove it worked.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.