This can be a big advantage if you don’t know the type of object you will be working with at compile time. These features can also make it possible to perform some interesting code tricks and reduce tedious casting operations if the language can work out how to use the type. Some developers feel dynamic languages can help them develop and prototype applications much quicker,and can be particularly suitable for testing and prototyping applications.The main disadvantage of working with dynamic languages is they of course lack compile time checks and generally have inferior performance when compared to static languages. When working with
dynamic languages, simple syntax errors and typos can stop your code working. I think anyone that has done any web development has spent much time tracking down such an error in JavaScript with its very helpful “object not set to an instance” message.
Is dynamic the Same as Var?
The var keyword is used the compiler infers the type of value you are using and writes the appropriate code for you when you compile the application. Variables declared using var benefit from type checks, Intellisense, and offer better performance than their dynamic equivalent.
Example of Dynamic
The below expel will return INT32,String.
dynamic myd = 100;
Console.WriteLine(myd.GetType().Name);
myd = "test";
Console.WriteLine(myd.GetType().Name);
One advantage is that it can avoid some tedious casting and Reflection code. For example, let’s say we want to create an instance of a type using a string and call a method on it at runtime.
In our example we will create a StringBuilder instance and call the Append method on it using Reflection:
object UsingReflection = Activator.CreateInstance(Type.GetType("System.Text.StringBuilder"));
Type ObjectType = UsingReflection.GetType();
//Append has many overloads so we need to tell reflection
which type we will use
Type[] TypeArray = new
Type[1];
TypeArray.SetValue(typeof(string), 0);
var ObjectMethodInfo = ObjectType.GetMethod("Append", TypeArray);
ObjectMethodInfo.Invoke(UsingReflection, new
object[] { "alex"
});
Console.WriteLine(ObjectType.GetMethod("ToString", new
Type[0]).Invoke(UsingReflection, null));
Console.ReadKey();
usingDynamic.Append("Hello");
Console.WriteLine(usingDynamic.ToString());
Console.ReadKey();
Dynamic
Limitations
When
working with dynamic objects, there are a number of constraints you should be
aware of:
- All methods and properties in classes have to be declared public to be dynamically accessible.
- Dynamic objects cannot be passed as arguments to other functions.
- Extension methods cannot be called on a dynamic object and a dynamic object cannot be passed into extension objects.
- Annoyingly, these restrictions stop you calling an extension method on a dynamic object.
No comments:
Post a Comment