Author avatar

Dániel Szabó

Dynamic Types in C#

Dániel Szabó

  • Jan 21, 2020
  • 4 Min read
  • 454 Views
  • Jan 21, 2020
  • 4 Min read
  • 454 Views

Introduction

In the fall of 2009 Microsoft released version 4.0 of C#, which included multiple new features such as Named and Optional Parameters, Dynamic Types, Variance, and COM Interoperability. All these features gave new ways to developers to overcome problems in a more elegant a sophisticated way. This guide will introduce you to Dynamic Types and teach you how to wield this powerful feature.

Dynamic typing may be very familiar to you if are already experienced in Python Programming Language. This type is a static type, but an object of type dynamic allows you to bypass static type checking, which happens and compile time, and to assign a type to a variable during runtime. As with everything else, it has it's ups and downs too. Dynamic types are very similar to Reflection, which is also evaluated at runtime, but has more performance impact.

Multiple Dispatch

When you are developing with Object Oriented Programming (OOP), a specific implementation of a virtual or abstract method is called at runtime based on your runtime type of the object or objects passed as this to one of the member functions. Double dispatch is a specific case of this when you have two methods with the same name that behave differently based on the type of arguments.

Let's look at an example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System;

namespace Pluralsight
{

    public abstract class Base { }
    public class A1 : Base { }
    public class A2 : Base { }

    public class Test
    {
        public static void Main(string[] args)
        {
            Base a1 = new A1();
            Base a2 = new A2();

            Dispatcher(a1, a2); 
            Dispatcher(a2, a1); 
            System.Console.ReadKey();
        }

        public static void Dispatcher(Base a1, Base a2) 
        {
            dynamic x = a1;
            dynamic y = a2;

            Method(x, y);

        }
        public static void Method(A1 a1, A2 a2) //1
        {
            Console.WriteLine("(A1,A2)");
        }
        public static void Method(A2 a2, A1 a1) //1
        {
            Console.WriteLine("(A2,A1)");
        }
    }

}
csharp

Here we have two classes defined as A1 and A2 that inherit from the Base abstract class. In our main function we instantiate these classes, then call our method, Dispatcher, with our instances in a different order. This method is special because it creates our x and y variables, which allow us to demonstrate the power of dynamic types. Then, in the same method, we call Method, which will behave differently based on the arguments. The first Dispatcher(a1, a2); call will return (A1,A2)as the order of the passed arguments and matches the //1 definition of Method. The second call, Dispatcher(a2, a1);, will return (A2,A1), as that is the order matching the //2 definition of Method. This could have many use cases, and it is very similar to implementing the switch construct.

Square Root

This example is about a small function we want to use to calculate the square root of a specific number. The Math.sqrt() function expects a variable of type float, and this is where dynamic types come to the rescue.

Let's look at another example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System;

namespace Pluralsight
{
    
    public class Test
    {
        public static void Main(string[] args)
        {
            decimal foo = 10;            
            double sroot = Math.Sqrt(foo);
            System.Console.WriteLine($"The square root of {foo} is {sroot}!");
            System.Console.ReadKey();
        }
    }
}
csharp

This is going to fail to compile as the compile-time type checking identifies that the type decimal cannot be converted to double. However, if we swap out the decimal foo = 10; to dynamic foo = 10; the compile time error goes away and the following result is produced.

1
The square root of 10 is 3.16227766016838!
bash

Conclusion

Dynamic typing allows faster development while sacrificing some speed, while static typing allows for faster and more reliable code with easy-to-hunt down bugs and problems. All in all, this is a very cool feature that altogether improves the C# experience and is widely used by developers since the pros outweigh the cons. I hope this has been informative to you and I would like to thank you for reading it.

2