17. Dynamic Programming

About this Tutorial

Objectives

Delegates will learn to develop applications using C# 4.5. After completing this course, delegates will be able to:

  • Use Visual Studio 2012 effectively
  • Create commercial C# Web Applications
  • Develop multi-threaded applications, Use WCF and LINQ

Audience

This course has been designed primarily for programmers new to the .Net development platform. Delegates experience solely in Windows application development or earlier versions of C# will also find the content beneficial.

Prerequisites

No previous experience in C# programming is required. But any experience you do have in programming will help. Also no experience in Visual Studio is required. But again any experience you do have with programming development environments will be a valuable.

Download Solutions

HTML tutorial


Overview
Visual C# in 2010 introduced a new type available to program, this was the dynamic type. This type is static but at object level will go over the static type checking. This means it will function like an object but will be allowed to support any operation at compile time. However, if the code is not valid, errors must be caught at run time.

Estimated Time – 1 Hour

Lab 1: Using the Dynamic Keyword

Lab 1: Using the Dynamic Keyword

Overview

  1. Static typing:
    • C# has always been a statically-typed language:
      • The compiler knows exactly what type a variable is.
      • Even if you use var.
    • Benefits of static typing:
      • Compile-time type safety.
      • IntelliSense.
    • Disadvantages of static typing:
      • You have to tell the compiler exactly what everything is.
      • Can cause ugly casts sometimes.
  2. Dynamic Typing:
    • .NET 4 introduced the concept of dynamic typing:
      • Declare variables using the dynamic keyword.
      • The compiler doesn’t know the type.
    • You can assign any type to a dynamic variable:
      • The type is determined at run time.
      • as a strong data type, not just Object.
    • Benefits of dynamic typing:
      • Easier integration with dynamic languages, e.g. Ruby and Python.
      • Easier late-bound method calls (via reflection) to COM.
  3. Additional Considerations:
    • You can declare dynamic variables with any scope:
      • Local variables.
      • Class-scope variables.
      • Properties.
      • Method parameter types.
      • Method return types.
    • But note:
      • Can’t use lambda expressions in methods calls on dynamic data.
      • Can’t use LINQ queries on dynamic data.
Lab
  1. We are now going to create a little example of how the dynamic keyword works in C# and can be used widely throughout when creating your applications.
  2. Start Visual Studio, New Project C#>Windows>Console Application and call this DynamicDemo
  3. We are only going to be using program.cs but hopefully will be able to show you exactly how dynamic variables work.
  4. Now add this code to Main() and we will create the methods later.
    DemoDeclaring();
    DemoAccessingMembers();
    DemoRunTimeExceptions();
  5. View code file.
  6. To create the first method we will just make a dynamic variable and show how easy it is to change the types of data that are held. All off this is done at runtime and wont cause any compilation errors –
    private static void DemoDeclaring()
    {
     ...
     // Declare a dynamic variable and assign it a string initially.
     dynamic t = "Hello world!";
     Console.WriteLine("t is of type: {0}", t.GetType());
     // Now assign an int to the dynamic variable.
     t = 180;
     Console.WriteLine("t is of type: {0}", t.GetType());
     ...
    }
  7. View code file.
  8. For the second method you will see that it works exactly the same to use the dynamic variable as if it was as that type of variable
    private static void DemoAccessingMembers()
    {
     ...
     // Declare a dynamic variable and assign it a string initially.
     dynamic t = "Hello world!";
     t = t.ToUpper();
     Console.WriteLine("t is {0}", t);
     ...
     // Now assign a List to the dynamic variable.
     t = new List<string>();
     t.Add("Huey");
     ...
     Console.WriteLine("t has {0} items", t.Count);
    }
  9. View code file.
  10. Now the last method will show you one of the problems of dynamic variables; this is because they are not compiled it is easy to get a runtime error from it handling the wrong operation –
    private static void DemoRunTimeExceptions()
    {
     ...
     // Declare a dynamic variable and assign it a string initially.
     dynamic t = "Hello world!"; // It's a string :-)
     t = t.ToUpper();// This will work fine.
     t.Add("Huey");// This will cause an exception.
     Console.WriteLine("t is {0}", t);
    }
  11. View code file.
  12. On running the application you should receive something similar to this –
    app1
  13. And then this error
    problem1

Lab 2: Dynamic Language Runtime (DLR)

Lab 2: Dynamic Language Runtime (DLR)

Overview

  1. The Dynamic Language Runtime (DLR) appeared in .NET 4:
    • Complementary runtime environment to the CLR.
    • Akin to dynamic runtimes in other languages (e.g. Ruby, Python).
  2. What’s the purpose of the DLR?
    • Allows a dynamic language to discover type information entirely at run time, with no compile-time checks.
  3. Features of the DLR:
    • Allows code-refactoring without extensive changes to code base.
    • Simplifies interop with diverse object types (e.g. COM).
    • Allows you to add/remove type members, in memory, at run time.
  4. Expression Trees:
    • The DLR uses “expression trees” to capture the meaning of a dynamic call, in neutral terms.
    • For example, consider this C# code:
      dynamic d = GetSomeData();
      d.SomeMethod(12);

      • The DLR will build an expression tree that says –
      • Call SomeMethod() on some object d, passing 12 as an argument.
      • This information is known as a “payload”.
    • The payload is passed to the correct runtime binder:
      • To IDispatch interface (if dynamic data points to COM object).
      • To IDynamicObject interface (if object implements this i/f).
      • To the C# runtime binder (in all other cases).
Lab
  1. You can use the DLR to simplify late-bound calls – See the LateBoundCalls.sln which can be downloaded from the solution.
  2. The main part of the solution to pay attention to is the DemoDynamicTyping() method where we can use a dynamic variable to hold an instance of the math utilities and then call he relevant methods from within that –
    private static void DemoDynamicTyping()
    {
     Console.WriteLine("\nUsing dynamic typing");
     Console.WriteLine("====================");
     Assembly asm = Assembly.Load("MyUtilities");
     try
     {
      // Get metadata for the MyMathUtilities type.
      Type math = asm.GetType("MyUtilities.MyMathUtilities");
      // Create a MyMathUtilities object on the fly.
      dynamic obj = Activator.CreateInstance(math);
      // Invoke method (with parameters).
      Console.WriteLine("Result is: {0}", obj.Add(10, 70));
     }
     catch(Exception ex)
     {
      Console.WriteLine(ex.Message);
     }
    }
  3. View code file.
  4. The results of running the application should look like this where they both have the same answer but are done slightly differently –
    app2
Well done! You have completed the C# course.
How do I get a certificate of Completion for this course?
  1. Once you have subscribed, TalkIT can monitor some of your activity on the website. But as the tutorials are designed to allow you to work when you want, we do not know exactly when you have finished a course – So just email TalkIT with:
    • The date you have completed all the tutorials in the course
    • Include the title of the course
  2. TalkIT will then send you a certificate of completion for that course

 

Back to beginning
Copyright © 2016 TalkIT®






If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top