Friday, July 2, 2021

Difference between object and dynamic in c# | Object Vs Dynamic

As we know that object is a base class for the the types in c# i.e. object is a class and all the classes in .net framework derived from object. we can assign any value (either ValueType or ReferenceType) to object, similarly we can assign any value to the dynamic. but there are few difference in dynamic and object 
  • dynamic is not a type it's just a keyword which tells compiler to ignore compile time type checking and infer dynamic declared variable's type at runtime.
  • when you assign a value to dynamic variable and then you assign this variable's value to another variable who's type is similar to assigned value's type you don't need type casting (see the example below) but in case of object you need to type caste object variable to particular type otherwise you will get compile time error.
      public static void ObjectVsDynamic()
        {
            dynamic a = "hello";
            string str = a; // no casting
          
            Console.WriteLine(str);

            object b = "hello";
            string str1 = (string)b;// in case of object explicit casting required.
            Console.WriteLine(str1);
            Console.ReadLine();
        }

No comments:

Post a Comment

C# Record type: Something to remember while using record types

  Record in c# provide a concise and expressive way to create immutable data types, record is a keyword in c#, we can use this keyword with ...