by Edward
10 April 2009 10:22
As we know C# is an OOP language(object-oriented programming) used in the Windows ASP.NET framework, but the current version of C# 3.0 included some capabilities of functional programming to enable LINQ.
In version 4.0 the C# programming language continues to evolve, although this it is inspired by dynamic languages such as Ruby, Perl and Python.
Another paradigm that is driving language design and innovation is concurrency and that is a paradigm that has certainly influenced the development of Visual Studio 2010 and the .NET Framework 4.0.
That brings me to my post for today, where I want to give an overview of one of the new innovations, called “Dynamically Typed Objects”.
Dynamically Typed Objects
Currently in the latest version of C# 3.0 you need to get an instance of a class and then call the Add method on that class to get the sum of two integers. For Example:
Calculator calc = GetCalculator();
int sum = calc.Add(100, 200);
Our code gets all the more interesting if the Calculator class is not statically typed but rather is written in COM, Ruby, Python, or even JavaScript. Even if we knew that the Calculator class is a .NET object but if we don’t know specifically which type it is, then we would have to use reflection to discover attributes about the type at runtime and then dynamically invoke the Add method.
object calc = GetCalculator();
Type type = calc.GetType();
object result = type.InvokeMember(
"Add",
BindingFlags.InvokeMethod,
null,
new object[] { 100, 200 });
int sum = Convert.ToInt32(result);
With C# 4.0 we would simply write the following code:
dynamic calc = GetCalculator();
int sum = calc.Add(100, 200);
In the above example we are declaring a variable, called calc, whose static type is dynamic. We’ll then be using dynamic method invocation to call the Add method and then dynamic conversion to convert the result of the dynamic invocation to a statically typed integer.