Wednesday, January 2, 2013

C#.net - Dynamic Keyword in C#.net

Dynamic type allows you to write code that will bypass compile time type checking.The Compiler will assume that whatever operation is defined for an object of type Dynamic is valid. if the operation isn't valid,the error won't be detected until runtime.

In Short Dynamic keyword gives you the ability to create objects dynamically at runtime, gives you the ability to call something you already know that it is existing but at runtime not at compile time.

In this article I will show you how to Open and Close Window using dynamic Keyword with the help of Generic Type.

Step 1
Create a WPF Application and give the solution name as SolDynamic.

Step 2
Add two Window in Solution,it is look like this


  
Click on Image for better View.

Step 3
Add a Single Button on Both Window,it is look like this

Window 1
<Grid>
        <Button x:Name="btnOpenWindow2" Content="Open Window 2" Width="150" Height="25" Click="btnOpenWindow2_Click"></Button>
 </Grid>


Window 2
<Grid>
        <Button x:Name="btnOpenWindow1" Content="Open Window 1" Width="150" Height="25" Click="btnOpenWindow1_Click"></Button>
</Grid>


Step 4
Create a static Class in solution for Opening and Closing Window,it is look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace SolDynamic
{
    public static class UIUtility
    {
        #region Methods

        /// <summary>
        /// Open Close Window Dynamically Using Dynamic Keyword
        /// </summary>
        /// <typeparam name="TOpen">Type Open Window</typeparam>
        /// <typeparam name="TClose">Type Close Window</typeparam>
        /// <param name="OpenWindowObj">Specify the Open Window Object</param>
        /// <param name="CloseWindowObj">Specify the Cloes Window Object</param>
        public static void OpenCloseWindow_Dynamic<TOpen, TClose>(TOpen OpenWindowObj, TClose CloseWindowObj)
        {
            try
            {
                if (OpenWindowObj != null && CloseWindowObj != null)
                {
                    if (OpenWindowObj is Window && CloseWindowObj is Window)
                    {
                        dynamic DOpenWindowObj = OpenWindowObj;
                        dynamic DCloseWindowObj = CloseWindowObj;

                        DOpenWindowObj.Show();
                        DCloseWindowObj.Close();
                    }
                    else
                    {
                        throw new NotSupportedException("Specify Window Control Object Only.");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message); 
            }
        }

      
        #endregion
    }
}


Using the dynamic type does not make it type-safe, hence the compiler is bypassed and the compiler does not check if the Show() and Close() method exists.



Click on Image for better View.

You can notice intellisense is saying it is dynamic expression and operation will be resolved at runtime. intellisense is not work if you are using dynamic type.

Step 5
Now call this method on button click event,it is look like this

Window 1 
private void btnOpenWindow2_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UIUtility.OpenCloseWindow_Dynamic<Window2, Window1>(new Window2(), this);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message); 
            }
        }


Window 2
private void btnOpenWindow1_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UIUtility.OpenCloseWindow_Dynamic<Window1, Window2>(new Window1(), this);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message); 
            }
        }



Run the project.

Limitation of Dynamic Type.
A dynamic object does not support extension methods.Anonymous functions (Lambda Expression) also cannot be used as parameters to a dynamic method call,thus LINQ does not work well with dynamic object.Most LINQ calls are extension methods and Lambda expression are used as arguments to those extension methods.

Download
Download Source Code