Dynamic Type in C#, in comparison to var Type

Knowing the type of variable you are working with in C# and while programming in general is pretty important. You can’t add a double and an integer together and get an integer, without converting it. If you attempt to do this the compiler will throw an exception and you will not be able to run your program. However, if you use var to add a double and an integer together, then you would get back a double. The compiler binds a double type to the var type at compile time.

These 3 lines of code would fail:

[sourcecode language="csharp" padlinenumbers="true"]
double sx = 11.34F;
int ix = 1;
int vy = sx + ix;
[/sourcecode]

These 3 lines of code compile and run:

[sourcecode language="csharp"]
double x = 11.34F;
int y = 1;
var z = x + y;
[/sourcecode]

With var, what you associate it to must exist within the domain of your program and libraries. For example:

[sourcecode language="csharp"]
var dynamicVar = new dynamicClass();
dynamicVar.AddOne(addOneToIt)
[/sourcecode]

I set the dynamicVar of type var to an instance of my dynamicClass() and then use the reference to call the AddOne() method. If the AddOne() method did not exist, when I tried to compile it, I would get an exception. If you used the dynamic value type and attempt to use a method that does not exist it will compile. However, at it will throw an exception at runtime.

This means that it would be possible to code a system with only knowing the name of the method and whether it returns something back. Perhaps you have a very secure database or extremely sophisticated logic that you do not want anyone to see, loose control of or access. You could simply give them those 2 details and they could program the interface. Or, if you are bound by a license and can only install a single instance of the application, say on the production environment. You would be able to create s stub-like development environment for testing using only var and dynamic types.

Below is a short program that shows the use of the var and dynamic types:

[sourcecode language="csharp"]
public static void showSimpleExample()
{
    Console.Write("Enter a value to add 1 to: ");
    int addOneToIt = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("");
 
    //Compiler determines the type (in this case it is of type 
    //dynamicClass)...at compile time
    var dynamicVar = new dynamicClass();
 
    Console.WriteLine("{0} + 1 = {1}", addOneToIt, 
                              dynamicVar.AddOne(addOneToIt));
    Console.WriteLine("");
 
    Console.Write("Enter a value to triple: ");
    int tripleIt = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("");
 
    dynamic dynamicDynamic = new dynamicClass();
 
    try
    {
        //The CanAddAnythingHere() does not exist, 
        //but the program will compile.
        dynamicDynamic.CanAddAnythingHere();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        Console.WriteLine("");
        Console.WriteLine("Using a try/catch we can continue" +
                  " using the correct method, the answer is: ");
        Console.WriteLine("");
    }
 
    Console.WriteLine("{0} x 3 = {1}", tripleIt, 
                           dynamicDynamic.TripleIt(tripleIt));
    Console.ReadLine();
}
[/sourcecode]

It is good practice to put things within a try catch block to handle exceptions. If you use var or dynamic type, I recommend doing this in every case.

And the code to run it is a simple console application.

[sourcecode language="csharp"]
static void Main(string[] args)
{
    showSimpleExample();
}
[/sourcecode]

My opinion is that not knowing the type of data you are working with is a bad idea. You should avoid doing this. Details, details, details are what a developer and designer want and need to know. THe more ambigious the requirements are, the less able are the developers to anticipate errors and manage them. However, we live in an ever changing and complicated world. So use them wisely!

Download the source




Leave a Comment

Your email address will not be published.