dynamic vs object type
In simple language:
Assume we have the following method:
public static void ConsoleWrite(string inputArg)
{
Console.WriteLine(inputArg);
}
Object: the following code has compile error unless cast object to string:
public static void Main(string[] args)
{
object obj = "String Sample";
ConsoleWrite(obj);// compile error
ConsoleWrite((string)obj); // correct
Console.ReadKey();
}
dynamic: the following code compiles successfully but if it contains a value except string
it throws Runtime error
public static void Main(string[] args)
{
dynamic dyn = "String Sample";
ConsoleWrite(dyn); // correct
dyn = 1;
ConsoleWrite(dyn);// Runtime Error
Console.ReadKey();
}
With the advancement in C# language, we have seen the dynamic and object types. Here are the two types, as I learned by comparing these 7 points:
Object
- Microsoft introduced the Object type in C# 1.0.
- It can store any value because "object" is the base class of all types in the .NET framework.
- Compiler has little information about the type.
- We can pass the object type as a method argument, and the method also can return the object type.
- We need to cast object variables to the original type to use it and to perform desired operations.
- Object can cause problems at run time if the stored value is not converted or cast to the underlying data type.
- Useful when we don't have more information about the data type.
Dynamic
- Dynamic was introduced with C# 4.0
- It can store any type of variable, similar to how Visual Basic handles a variable.
- It is not type-safe, i.e., the compiler doesn't have any information about the type of variable.
- A method can both accept a Dynamic type as an argument and return it.
- Casting is not required, but you need to know the properties and methods related to stored type.
- The Dynamic type can cause problems if the wrong properties or methods are accessed because all the information about the stored value is resolved at run time, compared to at compilation.
- Useful when we need to code using reflection or dynamic languages or with the COM objects due to writing less code.
Hopefully, this would help somebody.
They're hugely different.
If you use dynamic
you're opting into dynamic typing, and thus opting out of compile-time checking for the most part. And yes, it's less performant than using static typing where you can use static typing.
However, you can't do much with the object
type anyway - it has hardly any members. Where do you find yourself using it? When you want to write general purpose code which can work with a variety of types, you should usually consider generics rather than object
.