Sunday, November 02, 2008

C# 4.0 : Dynamic Programming -- CTP Release

C# Chief Architect Anders Hejlsberg explained the future of C# in PDC2008.Initial CTP release of C# 4.0 has some features like

1. Dynamically Typed Objects.
2. Optional and Named Parameters
3. Improved COM Interoperability.
4. Co and Contra Variance.


Here I am going to explain about Dynamic Programming.

Dynamically Typed Objects:

Here is the code for traditional way of calling typed object methods.

EmployeeInfo eInfo = new EmployeeInfo();
eInfo.EmployeeID = 1;
eInfo.FirstName = "Ayyanar";
eInfo.LastName = "Jayabalan";

Employee emp = GetEmployee();
bool affected = emp.AddEmployee(eInfo);



From the above code, we know the type "Employee" to call the AddEmployee methods.

if we does not know the Type("Employee"), we can use Reflection to call the AddEmployee method.

Here is the code to call the method using Reflection.


object refEmp = GetEmployee();

Type type = refEmp.GetType();

object objAffected = type.InvokeMember("AddEmployee", System.Reflection.BindingFlags.InvokeMethod, null, null, new object[] { eInfo });

bool affected = (bool)objAffected;


C# 4.0:
-------

We can call method directly without using Reflection for UnKnown Typed object.


dynamic emp = GetEmployee();

bool affected = emp.AddEmployee(eInfo);



We have to declared as a "dynamic" for unknown typed objects.

Method calling decision taken at RUNTIME instead of COMPILE TIME.

And also, .Net does not throw error while compiling the code and does not provide INTELLISENSE for dynamic type.

2 comments:

Anonymous said...

Interesting feature.

I am working with Visual Studio 2010 Parallel Extension to exploit multicore microprocessors. They are really cool. I wish I knew Visual Studio 2010 final release date.
I am reading "C# 2008 and 2005 threaded programming", Gaston Hillar, Packt Publishing.

http://www.amazon.co.uk/2008-2005-Threaded-Programming-Beginners/dp/1847197108/ref=pd_rhf_p_t_1

Taking advantage of multicore microprocessors is awesome!

Ayyanar Jayabalan said...

Nice to hear !!!.