C#
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented C#
-
Section 4: Working with Data
-
Section 5: Error Handling
-
Section 6: Delegates and Events
-
Section 7: Async Programming
-
Section 8: More Language Features
-
Section 9: File I/O and Serialization
-
Section 10: Networking in .NET
-
Section 11: The .NET Ecosystem
-
Section 12: Memory and Performance
-
Section 13: Concurrency Beyond Async
-
Section 14: Reflection and Attributes
-
Section 15: Testing and Best Practices
-
Section 16: Design Patterns in C#
-
Section 17: Standard Library Deep Dive
-
Section 18: Data Structures and Algorithms in C#
-
Section 19: GUI and Desktop Development Overview
-
Section 20: Practical Projects
-
Section 21: More Practice Exercises
-
Section 22: More Standard Library and Text Processing
-
Section 23: More Design Patterns
-
Section 24: More Projects
-
Section 25: Interview Practice
-
Section 26: C# Keywords Reference (Modifiers)
-
Section 27: C# Keywords Reference (Statements)
-
Section 28: C# Keywords Reference (Operators)
-
Section 29: BCL: System.Collections.Generic
-
Section 30: BCL: System.Linq
-
Section 31: BCL: System.Threading
-
Section 32: BCL: System.IO
-
Section 33: BCL: System.Text and System.Text.Json
-
Section 34: BCL: System.Net.Http
-
Section 35: C# Language Specification Topics
-
Section 36: More Practice Exercises
-
Section 37: More Async Patterns
-
Section 38: More BCL: System.Reflection and System.Diagnostics
-
Section 39: Nullable Reference Types In Depth
-
Section 40: C# Records and Pattern Matching In Depth
-
Section 41: Dependency Injection Deep Dive
-
Section 42: More Interview and Whiteboard Practice
95: Dynamic Type Usage with dynamic
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
dynamicobject usingnew ExpandoObject(). - Assign the
nameto a property calledUserNameon that dynamic object. - Loop through the
attributesdictionary and dynamically add each key-value pair as a property to the object. (Hint: You'll need to cast theExpandoObjectto anIDictionary<string, object>to add properties via a loop). - In your
Mainmethod, callCreateProfilewith a dictionary containing at least three different custom attributes. - Print out the
UserNameand one of the custom attributes directly from the resultingdynamicobject to prove it worked.
There are no comments for now.