Data Type - dynamic

Added in .NET 4.0
This introduced a new data type called "dynamic"
This data type tells the compiler that a variable's type might change and will not be known until run-time.
This is a static type which operates like the 'object' data type in most situations

The keyword dynamic is used in place of a data type.
If the code is not valid, errors are caught at run-time.
Any object can be converted to a dynamic data type.
You can use "dynamic" to access late binding

You can convert from implicit data types to a dynamic type

dynamic myVariable; 
myVariable = 12.34;
myVariable = "some text";

You can convert from a dynamic type to an implicit data type

dynamic myVariable; 
myVariable = "some text";
string myString = myVariable;

dynamic Properties=doc.customdocumentproperties 
for each (dynamic p in Properties)

This functionality is brought to you by the introduction of dynamic types.

We can use dynamic for a method parameter in place of an explicit data type.
We can create a method whose return data type is dynamic.

static dynamic Sum(dynamic var1, dynamic var2) 
   return var1 + var2;
int x=2;
int y=3;
int z = Sum(x,y); // 5

double x=2.1;
double y=3.1;
double z = Sum(x,y); // 5.2

Everywhere a type can be used, dynamic can be used instead
This can be used as a generic type
This can be used in parameter lists
This can be used in a class field

declare a variable as dynamic and SS the intellisense
The IDispatch interface is used in office automation utilities the dynamic dispatch approach

Late Binding

Visual Studio 2010 and Later

VBA can determine properties of objects at runtime.
A lot of the Office objects return the type object which must be explicitley converted to the correct type.
VBA can determine properties of objects at run-time, effectively providing late binding between your code and the objects themselves.
A new data type called "dynamic" was added in Visual Studio 2010 to simplify late binding.
C# does not handle late binding

dynamic objDialog = Application.Dialogs[Word.wdWordDialog.wdDialogFilePageSetup]; 
objDialog.PageWidth = 10;
objDialog.PageHeight = 10;

Visual Studio 2008 and Earlier

You can use Reflection which allows you to dynamically determine available members of types and perform a type of late binding.
To handle late-bound objects you can use a simple wrapper to set the property values.

Word.Dialog objDialog; 
objDialog = Application.Dialogs(Word.wdWordDialog.wdDialogFilePageSetup);
InvokeHelper(objDialog, "Page Width", 10);
InvokeHelper(objDialog, "Page Height", 10);

private void InvokeHelper(
Word.Dialog objDialog,
string smember,
object objvalue)
System.Reflection.Type objType = typeof(Word.Dialog);
     System.Reflection.BindingFlags.SetProperty | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance,
     new object[] {objDialog.ToString()} );

© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext