C# Dynamic Keyword

C# Code Snippets Dynamic Keyword
Share:

About

In this code snippet, we will take a look at the dynamic keyword in C#.

Dynamic allows you to save any data type into a variable or pass any type into a method/return any type from a method.

By default, you should try and avoid using dynamic and only use it in some very limited cases. For example when/if you ever find yourself in a scenario(interopreflection, …) where you need to create a dynamic variable, method or parameter you should first ask yourself if you can somehow avoid it. If not then use dynamic but be aware that you will get an error only at runtime if you for example, try to access some property of an object that doesn’t exist.

Let’s have a look at the code below to see how to use the dynamic keyword.

Code:

using System;

namespace DynamicKeyword
{
    class Program
    {
        static void Main(string[] args)
        {
            //Any data type can be stored in this variable.
            dynamic myDynamicVariable;

            myDynamicVariable = "Some string";
            Console.WriteLine((string)myDynamicVariable);

            myDynamicVariable = 5;
            Console.WriteLine((int)myDynamicVariable + 5);

            Console.WriteLine(myDynamicMethod(5));

            Console.ReadLine();
        }

        public static dynamic myDynamicMethod(dynamic input) 
        {
            //This method does nothing except demonstrate how you can use dynamic.
            return input;
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger