C# Dynamic Tutorial: Dynamic Example C# with Real-World Use Case
Hey, there! 👋 Have you ever written code where you weren’t sure about the data type? Maybe the data comes from a user, a file, or an API, and you just want C# to figure it out at runtime. Well, that’s where the dynamic type comes in!
C# usually loves strict typing, meaning you have to declare data types explicitly. But with dynamic
, you get the freedom to change the type at runtime. Cool, right? 😃
Let’s break it down with a fun real-world scenario, examples, and a complete Dynamic Example C#. Ready? Let’s go! 🚀
What You Are Going to Learn in This Lesson?
✔️ What is the dynamic
type in C#?
✔️ When and why should you use it?
✔️ A real-world example to make it easy to understand.
✔️ A complete Dynamic Example C# with output.
✔️ Code explanation in simple words.
What is Dynamic in C#?
The dynamic
keyword allows you to skip specifying a data type. Instead, the type is determined at runtime. Think of it as a flexible variable that can change its type on the fly.
Real world example
Imagine you have a magic backpack 🎒 that can change its size and shape based on what you put inside. If you throw in a book 📚, it becomes a book bag. If you drop in a water bottle 🧴, it reshapes into a bottle holder. And if you stuff in a laptop 💻, boom! It transforms into a laptop bag.
That’s exactly how dynamic works in C#! It’s a special type that adapts at runtime—it can be a number, a string, a date, or even an object, depending on what you assign to it. Cool, right? 😃
Example: Dynamic in Action
using System;
class Program
{
static void Main()
{
dynamic myValue = 10;
Console.WriteLine($"Value: {myValue}, Type: {myValue.GetType()}");
myValue = "Hello, Dynamic!";
Console.WriteLine($"Value: {myValue}, Type: {myValue.GetType()}");
myValue = 3.14;
Console.WriteLine($"Value: {myValue}, Type: {myValue.GetType()}");
}
}
Output:
Value: 10, Type: System.Int32
Value: Hello, Dynamic!, Type: System.String
Value: 3.14, Type: System.Double
See what happened? We assigned an integer, then a string, and then a double—and C# just rolled with it! 🎉
Real-World Example: Using Dynamic in a Chatbot
Imagine you’re building a chatbot. Users can ask anything, and the bot’s response could be text, a number, or even an object. Instead of defining a fixed return type, we use dynamic
to handle any response type!
Dynamic Example C#: Chatbot Response
using System;
class Chatbot
{
public dynamic GetResponse(string question)
{
if (question.Contains("time"))
{
return DateTime.Now; // Returning a DateTime object
}
else if (question.Contains("pi"))
{
return 3.14159; // Returning a double
}
else
{
return "I don't know! 🤷♂️"; // Returning a string
}
}
}
class Program
{
static void Main()
{
Chatbot bot = new Chatbot();
dynamic response1 = bot.GetResponse("What is the time?");
Console.WriteLine($"Bot: {response1}, Type: {response1.GetType()}");
dynamic response2 = bot.GetResponse("What is the value of pi?");
Console.WriteLine($"Bot: {response2}, Type: {response2.GetType()}");
dynamic response3 = bot.GetResponse("Who is the president?");
Console.WriteLine($"Bot: {response3}, Type: {response3.GetType()}");
}
}
Output:
Bot: 2/14/2025 12:34:56 PM, Type: System.DateTime
Bot: 3.14159, Type: System.Double
Bot: I don't know! 🤷♂️, Type: System.String
How It Works?
✔️ The chatbot returns different data types based on the question.
✔️ It returns a DateTime if the question is about time.
✔️ It returns a number if the question is about Pi.
✔️ Otherwise, it returns a string.
That’s the power of dynamic
—it adapts as needed! 🤯
When Should You Use Dynamic?
🟢 Good Use Cases:
✅ When working with JSON, APIs, or Reflection where types are unknown.
✅ In chatbots, AI, or automation where responses vary.
✅ When using COM objects or dynamic data sources.
🔴 Avoid When:
❌ You need strict type safety.
❌ Performance is critical (dynamic can be slower).
❌ You want compile-time error checking (dynamic errors show up only at runtime).
Conclusion
So, what did we learn? Dynamic lets us skip specifying data types and adjusts at runtime. It’s super flexible and great for handling unknown or varying data types. However, use it wisely because C# loses some of its safety checks!
If you have difficulty or questions, drop a comment. We will be happy to help you. 😊
Next What?
Up next, we’re diving into “Global” expressions in C#. Ever wanted global variables or settings? Well, that’s exactly what we’ll explore next! Stay tuned, and let’s keep learning together! 🚀