Scott Dorman

ephemeral segment

  Home  |   Contact  |   Syndication    |   Login
  608 Posts | 11 Stories | 900 Comments | 51 Trackbacks

News


Post Categories

Image Galleries


Microsoft Store


Creative Commons License



Locations of visitors to this page

Subscribers to this feed

TwitterCounter for @sdorman

View blog authority

Add to Technorati Favorites

Windows Live Alerts

AddThis Social Bookmark Button

LinkedIn profile

Community Credit profile

The Code Project

Follow me on Twitter

Get Free Shots from Snap.com

Community Credit Hall of Fame

Get Feedghost

Xobni outlook add-in for your inbox



Support This Site

Tag Cloud


Article Categories

Archives

Post Categories

Image Galleries

If C# 3.0 was all about Language Integrated Query (LINQ), then C# 4.0 is all about dynamic programming. What exactly does that mean? It means that C# 4.0 brings some of flexibility and declarative style of programming to C#.

image

But what does that really mean?

To sum it up in one keyword: dynamic.

C# 4.0 is adding a new dynamic keyword which is used as a data type in much the same way the var keyword is used. Why is this important? The biggest reason is that it allows a C# program to use dynamic dispatch to more naturally create objects coming from a dynamic language.

For example, suppose you have a Calculator object declared in C#, meaning it is statically typed. You interact with your object like this:

Calculator calc = GetCalculator();
int sum = calc.Add(10, 20);

That’s pretty simple and straight forward. Now suppose the Calculator is not a statically typed .NET class (or it is a .NET class but you don’t know the specific type of class), you must do something like this:

object calc = GetCalculator();
Type calcType = calc.GetType();
object res = calcType.InvokeMember("Add",
    BindingFlags.InvokeMethod, null,
    new object[] { 10, 20 });
int sum = Convert.ToInt32(res);

That’s not nearly as simple. In fact, it’s downright ugly. There is a lot of non-type-safe calls and reflection going on here that you really shouldn’t have to see.

To take this a step further, if we knew that Calculator was a JavaScript class, you must use similar (but still significantly different) code:

ScriptObject calc = GetCalculator();
object res = calc.Invoke("Add", 10, 20);
int sum = Convert.ToInt32(res);

The reason for the differences in syntax is that there is no unification between the two APIs.

In C# 4.0, you can now use the following syntax:

dynamic calc = GetCalculator();
int sum = calc.Add(10, 20);

If you look at this syntax and the earlier statically typed call, you should notice that the only difference is that in C# we are declaring the data type to be dynamic.

image

Does this mean that C# is loosing it's roots as a statically typed language or that we should all start moving towards dynamic languages? Absolutely not. What is means is that it is now easier for you to write C# code that talks to objects (or APIs) written in dynamically typed languages. It also means that there is a unified API to talk to any dynamic language. You no longer need to worry about what language you are interoperating with to determine which C# code you must write.

So how does the dynamic keyword work? As I mentioned, it's a keyword in a similar fashion to var. You declare at compile-time the type to be dynamic, but at run-time you get a strongly typed object.

image

The dynamic keyword is great for writing C# code that consumes a dynamic object, but what about going the other direction and writing C# code that can be called from a dynamic language? You do this by implementing the IDynamicObject interface (or more simply, inheriting from the abstract DynamicObject class) and providing your own implementation for the member lookup and invocation.

Using the features and capabilities of the new dynamic keyword, the IDynamicObject interface, and the fact that the dynamic dispatch can dispatch to both dynamic and static types, C# effectively gets support for duck-typing.

Technorati Tags:
DotNetKicks Image
posted on Sunday, November 16, 2008 10:11 AM

Feedback

# re: C# 4.0: Dynamic Programming 11/16/2008 12:50 PM Catto
Hey Now Scott,
that is pretty good info.

Thx,
Catto

# re: C# 4.0: Dynamic Programming 1/19/2009 4:17 PM Dan
Hi Scott,

Can 'dynamic' type for Generic?
For example, List<dynamic>??

Thanks,

Dan

# re: C# 4.0: Dynamic Programming 3/13/2009 5:09 PM Janus007
Well, I can see a some nice scenarios to use this.

But I had hoped for something much more powerful

private string Foo(int x)
{
return x + 10;
}

public DoSomeThing(Method name)
{
var fooValue = name(10);
}

public Caller()
{
DoSomeThing("Foo");
}

That's what I call dynamic OR even more useful, dynamics for class names also.


# re: C# 4.0: Dynamic Programming 7/29/2009 10:10 PM rei
Dan: I think you can.

Lots of info here in this video: http://channel9.msdn.com/shows/Going+Deep/Inside-C-40-dynamic-type-optional-parameters-more-COM-friendly/

# re: C# 4.0: Dynamic Programming 10/28/2009 4:50 PM JZ
@ Janus007
Little more powerful dynamic programming....still not quite what you wanted.

static void Main(string[] args)
{
dynamic obj = new ExpandoObject();
obj.Foo = (Func<int,string>)((integer)
=> { return (10 + integer).ToString(); });
obj.DoSomeThing = (Func<Func<int, string>, string>)((action)
=> { return action(10); });
Console.WriteLine(obj.DoSomeThing(obj.Foo));
}

# re: C# 4.0: Dynamic Programming 11/2/2009 1:45 AM Aaron Lu
Thx for offering so nice article.
The examples made me be clear about the reason why dynamic is brought to C#4.0 :).


# re: C# 4.0: Dynamic Programming 2/7/2010 9:38 AM Bilal Nazer
dynamic in C# 4.0 was buzzword for me before reading this article.
Nice article. Nice Job.

# re: C# 4.0: Dynamic Programming 3/13/2010 6:36 AM British Developer
Sounds clever. Still not 100% when I would practically use the dynamic type though. Oh well - I'll be upgrading soon. Guess I'll find out :)

# re: C# 4.0: Dynamic Programming 5/6/2010 9:17 PM Night Owl Coders
Another interesting article on .NET 4.0 dynamics can be seen here (http://nightowlcoders.blogspot.com/2010/05/building-better-dynamic-net-40.html) This outlines how to take advantage of string based property access across a dynamic object. This is a really powerful combination when put along side other features using Dynamics.

Check it out and feel free to follow!

~Night Owl Coders~

# re: C# 4.0: Dynamic Programming 5/21/2010 7:04 AM square root calculator
I thought it was going to be some boring old site, but I'm glad I visited. I will post a link to this site on my blog. I believe my visitors will find that very useful.


# re: C# 4.0: Dynamic Programming 10/23/2010 1:29 AM divemaster
Honestly, I'm that good in programming nor in any computer related stuffs so I usually do my research to learn more about these things. Reading is a bit confusing at first but eventually helped me to understand some points in programming. Looking forward to more of your tutorials.

# re: C# 4.0: Dynamic Programming 11/5/2010 9:02 AM NLP
C# for sure is an interesting programming i tried to learn once and made a pretty little software but is hard to learn it with books and by yourself without any guidance.

# re: C# 4.0: Dynamic Programming 12/3/2010 3:57 AM magesh
What is the type of Dynamic, where value type or reference type

# re: C# 4.0: Dynamic Programming 10/21/2011 1:20 AM ANI
That's great explanation.

# re: C# 4.0: Dynamic Programming 9/24/2012 9:15 AM Emdadul Islam
i like this program.................

# re: C# 4.0: Dynamic Programming 3/12/2013 9:25 AM john net
I read 3 other posts about dynamic, and really, this one is very clear. Thank you.

# re: C# 4.0: Dynamic Programming 5/6/2013 7:26 AM LoganHill
Its important that if you do not know much about it to get it learnt by any reputed master. Like I have been taking NLP through coaching courses Sydney to get complete perfection.

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: