Dynamic Keyword in C#

Introduction

C# is a strongly-typed language. What does it mean? It means, in C#, every variable and constant has a pre-defined type. Before you use any variable, you must tell the compiler what type of value a variable will store.

Let's talk a real-world example.

Our world is filled with the containers. A container can be a truck carrying dirt. A container can be a milk box or even a cup of tea. Some of the containers in our world are pre-defined what they can store and what not. Let's call them predefined containers. For example, a gasoline container is usually designed to carry gasoline. But most of the containers in our world are multi-purpose. For example, in a bowl, we can store water, milk, tea or even sugar. Depending on the size of the container and fruits, we can even store some fruits in a bowl. So, in this case, a bowl is a all-purpose container. To compare with the real world, in C# language, most of the constants and variables are predefined containers. But what if you want to use a variable as an all-purpose container?

What if you are not sure of the type of value you want to store in a variable? This is where dynamic programming is plays a vital role. Dynamic programming is supported by the dynamic keyword that was introduced in C# 4.0. If you're working with previous versions of C# language, you will not be able to use the dynamic keyword.

The dynamic keyword is used to declare dynamic types. The dynamic types tell the compiler that the object is defined as dynamic and skip type-checking at compiler time; delay type-checking until runtime. All syntaxes are checked and errors are thrown at runtime. The dynamic programming was introduced to provide a cross reference between .NET and non .NET APIs such as COM APIs, IronPython, and the COM version of the HTML Document Object Model (DOM).

The following code snippet declares a dynamic field, a dynamic property, a dynamic method and a dynamic variable.

// Define a dynamic field.
dynamic name;

// Define a dynamic property.
dynamic NameProperty { get; set; }

// Define a dynamic method with a dynamic parameter type.
public dynamic FullNameMethod(dynamic d)
{
    name = "Mahesh";
    dynamic firstname = name;
    string lastname = "Chand";
    return firstname + lastname;
}

As you may have noticed from the code above, a dynamic variable can store any type of value. A method can also return a dynamic type and also can accept dynamic parameters.

Here is an example with a dynamic variable that can store a string, an integer, a double, and a Boolean value.

dynamic dyno = "Mahesh Chand";
Console.WriteLine(dyno);
dyno = 38;
Console.WriteLine(dyno);
dyno = 44.95;
Console.WriteLine(dyno);
dyno = true;
Console.WriteLine(dyno);

Dynamic types can also be converted explicitly to other types and vice versa. The following code snippet converts a string, an integer, and a double type into dynamic types by casting them with the dynamic keyword.

dynamic d;
string name = "Mahesh Chand";
d = (dynamic)name;
Console.WriteLine(d);

int age = 38;
d = (dynamic)age;
Console.WriteLine(d);

double price = 44.95d;
d = (dynamic)price;
Console.WriteLine(d);

Dynamic can be used with classes too. The following example defines an Author class with a dynamic method FullNameMethod. The Main method creates a dynamic type of the Author class and calls its dynamic method by passing a dynamic parameter.

namespace DynamicProgSample
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic lastName = "Chand";
            dynamic dynAuthor = new Author();
            Console.WriteLine(dynAuthor.FullNameMethod(lastName));

            Console.ReadKey();
        }
    }

    public class Author
    {
        // Define a dynamic field.
        dynamic name;

        // Define a dynamic property.
        dynamic NameProperty { get; set; }

        // Define a dynamic method with a dynamic parameter type.
        public dynamic FullNameMethod(dynamic d)
        {
            name = "Mahesh";
            dynamic firstname = name;
            return firstname + " " + d;
        }
    }
}

Summary

Dynamic programming has added a new dimension to the C# language. It plays a vital role in key technologies such as LINQ. In this article, we learned about the dynamic keyword and how to define dynamic variables in the C# language.


Recommended Free Ebook
Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.