Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Declaration of Dynamic Variable
3.
Dynamic Type Conversion
4.
Methods and Parameters
5.
FAQs
5.1.
What are dynamic type variables?
5.2.
Is it good to use dynamic type in C#?
5.3.
What is the dynamic type in C#?
5.4.
What is serialization in C#?
5.5.
What is dynamic typing and static typing?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

C# Dynamic Type

Author Alok Pandey
1 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

 

Introduction

Dynamic is a new type introduced in C# 4. It's a static type, but unlike other static types, the (potential) members of a dynamic object is not checked by the compiler. In most circumstances, it behaves as if it were an object. A dynamically typed element is assumed to support any action at compile time. The compiler does not check the type of the dynamic type variable at compile time, instead, the type is obtained at run time. The dynamic keyword is used to construct the dynamic type variable.

Example: dynamic Variable

dynamic MyDynamicVar = 1;

Recommended Topic, Palindrome in C#, singleton design pattern in c#, and Ienumerable vs Iqueryable.

Declaration of Dynamic Variable

The dynamic keyword enables you to use variables that are not type-specific and instead act as the type of data they contain. You may easily assign a new value to a dynamic variable, and if the type of value you're assigning isn't the same as the one it already has, the dynamic variable will immediately change the type. When we declare a variable dynamic, we're effectively telling the compiler to disable compile-time type checks. Dynamic is basically System. Object type under the hood, however, it is not necessary to cast a value before using it. Let's see this with an example.

// C# code to explain how to get the dynamic type variable's actual type.

using System;
class CodingNinjas{
// Main Method
static public void Main()
{
	// Dynamic variables
	
	dynamic value = true;
	Console.WriteLine("Type of value: {0}", value.GetType().ToString());

	value = 189234;
	Console.WriteLine("Type of value: {0}", value.GetType().ToString());
 
    value = 8952.58;
    Console.WriteLine("Type of value: {0}", value.GetType().ToString());
    
  	value = "CODINGNINJAS";
  	Console.WriteLine("Type of value: {0}",value.GetType().ToString());
	}
}

 

Output

Type of value: system. Boolean
type of value: system. Int32
type of value: system. Double
type of value: system. String

 

In the above example, there is one variable that is of dynamic type, and it takes all types of values such as int, bool, string, etc

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Dynamic Type Conversion

Dynamic types alter types dependent on the provided value at runtime. The following example demonstrates how a dynamic variable's type varies depending on its value. The dynamic type variables are converted to other types implicitly.

using System;
class CodingNinjas{
// Main Method
static public void Main()
{
        dynamic d1 = 200;
        int i = d1;
        
        d1 = "CodingNinjas";
        string greet = d1;
       
        d1 = DateTime.Now;
        DateTime dt = d1;
}
}

Methods and Parameters

The C# compiler does not check for the number of parameters, parameter type, or non-existence. It checks these items at runtime and throws a runtime exception if they aren't correct. Let's try to understand this by example


// C# code that shows how to provide dynamic type arguments into a method.

using System;
class CodingNinjas {
// Method which contains dynamic parameters
public static void addstr(dynamic s1, dynamic s2)
{
Console.WriteLine(s1 + s2);
}


// Main method
static public void Main()
{


// Calling addstr method
addstr("C", "N");
addstr("Coding", " Ninjas");
addstr("Coding", 5252);
addstr(10, 30);
}
}

 

Output

Cn
coding ninjas
coding5252
40

 

In the above example, the compiler does not check the parameter type and performs an addition operation on the given parameter.

FAQs

What are dynamic type variables?

The dynamic keyword is used to define dynamic type variables. dynamic DynamicVar = 1; In most circumstances, the compiler converts dynamic types to object types. The actual type of a dynamic type variable, on the other hand, would be resolved at runtime.

Is it good to use dynamic type in C#?

Because of the need to better interoperability with COM (Component Object Model) and other dynamic languages, the dynamic type has been added to C# since version 4. While reflection can do this, dynamic provides a more natural and intuitive technique to accomplish the same goal.

What is the dynamic type in C#?

A new type known as a dynamic type is introduced in C# 4.0. It is used to circumvent type verification at compile time. The type of the dynamic type variable is not checked by the compiler at compile time; instead, the type is obtained at run time.

What is serialization in C#?

The process of transforming an item into a stream of bytes in order to store or transport it to memory, a database, or a file is known as serialization. Its major purpose is to save the state of an object so that it can be recreated later. Deserialization is the opposite of serialization.

What is dynamic typing and static typing?

Type checking is done at compile time in statically typed languages and at run time in dynamically typed languages. You must declare the data types of your variables before using them in statically-typed languages, but not in dynamically-typed languages.

Conclusion

In this article, we have extensively discussed C# Dynamic Type.

We hope that this blog has helped you enhance your knowledge regarding  C# Dynamic Type and if you would like to learn more, check out our articles on  

C# ConstructorC# Functions

 

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. 

Enroll in our courses and refer to the mock test and problems available.

Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow. 

Happy Coding!
 

Live masterclass