Tuesday, August 3, 2010

Dyanamic And Object Keywords in C#

C# 4.0 has provided dynamic keyword to define variables.Object keyword is defined already in c# 1.0.

So, I will define object
object obj = 10;

When you add value to object 'obj' by 10,
// A compiler error, because
// at compile time the type of obj is System.Object.
obj = obj + 10;
It's failed because of datatype conversion.
// You need to explicitly cast obj to a necessary type.
obj = (int)obj + 10;


Let's define dynamic keyword now

dynamic dyn = 10;//dyn as dynamic.

//Adding value to dynamic variable.

dyn = dyn + 10;

// Also, this operation will succeed for all numeric
// or other types that support a “+” operation.
dyn = 10.0;
dyn = dyn + 10;

So, By defining as dynamic,it will automatically determine compatible datatype on runtime.


Thanks.

Aravind
aravindbenator@gmail.com

No comments:

Post a Comment