Alpesh Maniya
What is the difference between object and dynamic?
By Alpesh Maniya in .NET on Jan 18 2024
  • Jayraj Chhaya
    Jan, 2024 29

    In Dot net, both object and dynamic are used to represent values of unknown or varying types. However, there are some key differences between them.

    The object type is a reference type that is the base type for all other types in Dot net. It can hold values of any type, as it is a universal type. However, when we use an object, we lose the ability to access the members or properties specific to the actual type of the object. We need to explicitly cast the object to the desired type before accessing its members.

    On the other hand, the dynamic type is a type that is resolved at runtime. It allows us to write code that can interact with objects whose types are not known until runtime. With dynamic, we can access the members and properties of the object without explicit casting. The type checking is done at runtime, which means that any errors related to type mismatch will be caught at runtime.

    1. object obj = "Type Object";
    2. dynamic dyn = "Type Dynamic";
    3. // Accessing members using object
    4. string objValue = (string)obj; // Explicit casting required
    5. int objLength = objValue.Length; // Accessing members after casting
    6. // Accessing members using dynamic
    7. string dynValue = dyn; // No casting required
    8. int dynLength = dynValue.Length; // Accessing members directly

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS