Net-informations.com
SiteMap  | About    

Dynamic Data Type in C#

The dynamic keyword brings exciting new features to C# 4. Dynamic Type means that you can store any type of value in the dynamic data type variable because type checking for dynamic types of variables takes place at run-time. In order to use the dynamic type in C#, you use the dynamic keyword in place of another type name.

The key to the dynamic type is that the type checking is disabled until run-time. When you use the dynamic keyword you tell the compiler to turn off compile-time checking . So, it is not type safe i.e. Compiler doesn't have any information about the type of variable. This can produce problems if the run-time type does not support the members that are called.

The reason is that the compiler doesn't know the runtime type of the object and therefore can't tell you that the increment operation is not supported in this case. Absence of compile-time type checking leads to the absence of IntelliSense as well. Because the C# compiler doesn't know the type of the object, it can't enumerate its properties and methods. This problem might be solved with additional type inference , as is done in the IronPython tools for Visual Studio, but for now C# doesn't provide it.

Dynamic type as Parameter

Dynamic type can be passed as method argument so that it can accept any type of parameter at run time.

Example

Casting is not required but you need to know the properties and methods related to stored type. It is effectively inherit the properties and methods appropriate to their type at runtime. The following code will run because str is a string at the point the Length property is used, for example:

Limitations

In most situations it would be inadvisable to use the dynamic type unless you are integrating with a dynamic language or another framework where types are not known at compile time. Because the compiler does not know what type the dynamic variable will eventually become, so it’s unable to offer method or property code hints in Visual Studio.

Value Type and Reference Type

The Types in .NET Framework are either treated by Value Type or by Reference Type. A Value Type holds the data within its own memory allocation and a Reference Type contains a pointer to another memory location that holds the real data. More on... Value Type and Reference Type









net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.