I guess that most of you have already heard about Anders Hejlsberg introduction to the future of C#, taken place at PDC 2008. One of the core features introduced in C# 4.0 is called Dynamic Lookup which allows a unified approach to invoking things dynamically. Currently, when you call object methods or properties, the compiler checks that they exist and raises an error if they do not. With dynamic lookup, you can call any method or property, and they are not checked until runtime. C# 4.0 is extending towards the dynamic languages. Having an object, you do not need to worry about whether it comes from COM, Python, JavaScript or reflection, you just apply operations to it and leave it to the runtime to figure out what exactly those operations mean.


C# 4.0 will support dynamic typing through a new static type called “dynamic”. As already described, when you have an object of type dynamic you can do whatever you like with it, those operations are resolved only at runtime. Lets first see a method declaration:

public dynamic GetService()
    // Getting some service...

and how to use it:

dynamic service = GetService();

The C# compiler allows you to call a method with any name and any arguments because service is declared as dynamic. Scary, isn’t it? Only at runtime will you get an error if the returned object doesn’t have such a method.



What shall I do with the GetService Method? I don’t know and neither does IntelliSense. If I mistakenly call a non existing method or even had a typo while typing an existing method, I will get a runtime error while I could know about my mistake at compile time. I can’t see one good thing here. The problem is that when running our program, we never reach all of the paths so we might never face our problem, our customer will. If it is up to me, I won’t use this feature, but I am not alone, there are third party libraries and co workers who might use the dynamic keyword and make me helpless. The dynamic keyword is open to abuse as anything could be. This feature moves us away from strong typing meaning that many years of wisdom is being thrown out of the window. What is wrong about interfaces? It gives flexibility but it keeps us from stupid mistakes as well.

I heard that Hejlsberg noted that developers should not now declare all variables as dynamic, but should continue to rely on static typing as standard, because this is safer and faster. Do you really trust C# developers so much? It makes me cringe. You can’t provide a heavy tool for everybody, many developers won’t use it correctly and wisely and the other developers will suffer from their stupidity. Why leaving an open door for unnecessary mistakes? Why?

There are some more features in C# 4.0 like Named and Optional Arguments, Covariance and Contravariance for generic types. I decided to focus on the dynamic lookup feature because I am really afraid from its consequences and can’t understand what is the benefit of it. Do you agree with me? Don’t you agree and think that I am paranoid? Comment and start a debate.

Tags :

44 Responses to “C# 4.0 Dynamic Lookup – Are You Kidding Me?”

  1. Will

    Said on November 3, 2008 :

    Morons do moronic things, and only a moron would declare everything as dynamic. They also do other stupid, dangerous things in code. What’s the big deal.

    Dynamic objects are supposed to ease interop with win32 COM objects that don’t have a strongly typed API and other dynamic languages in the .NET framework. If you’ve never done this, you wouldn’t understand how its near impossible (or at least damn hard) to do this in a strongly-typed world.

    Also, imagine C# as a scripting language… beautiful.

  2. Hüseyin Tüfekçilerli

    Said on November 3, 2008 :

    This was great news from my point of view. Since we are doing a lot of COM interop work and Office development at work, it will help our code to be more clean and understandable. Today we can do these calls but it needs Reflection which makes code unnecessarily long.

    Another great feature for us (COM interop users) is Type Embedding and Equivalence:

  3. configurator

    Said on November 3, 2008 :

    Start thinking a bit more outside the box; maybe there are cases where dynamic objects can help you?
    If you’ve ever done COM or Office interop you would know that it’s a damn nightmare. Try communicating with functions defined in dynamic languages in the DLR? Yeah, right. ‘dynamic’ is not there as a hammer-for-every-nail. It is there because we need it. We need where we would otherwise need reflection. It is something that you will (or should) rarely use, but when you do, it is extremely useful.

  4. Judah

    Said on November 3, 2008 :

    I would agree with you if some fool declared everything as dynamic.

    If it’s used for what it’s intended for — interoping with COM and dynamic languages — then it’s good, then it makes the world better.

  5. Billy Biro

    Said on November 3, 2008 :

    I agree that Dynamic Lookup can help greatly with COM interop, but seriously, after over 7 years of the .NET Framework, isn’t about time that COM died the death it deserves?

  6. Nikhil Kothari

    Said on November 3, 2008 :

    I think judicious use of dynamic helps cleanup code that would otherwise be littered with strings and late-bound lookups anyway. The same, no more, no less, late-bound lookups are still there, but the code is more readable.

    The debate on dynamic is certainly just starting :-)
    I posted a sample at http://www.nikhilk.net/CSharp-Dynamic-Programming-JSON.aspx just this morning.

  7. RickyAH

    Said on November 3, 2008 :

    Somebody here has never used LateBinding calls over Automation objects in C# ;)

    The “dynamic” keyword is “available” in VB.NET already and it’s even easier to use:
    object service;

  8. Jonathan Allen

    Said on November 4, 2008 :

    > If I mistakenly call a non existing method or even had a typo while typing an existing method, I will get a runtime error while I could know about my mistake at compile time. I can’t see one good thing here.

    We are talking about dynamic objects here. By definition you don’t know whether or not a method exists until runtime. And even then, a method can created or destroyed at a whim.

    Do you work with XML? Well sometimes the tags you are expecting are missing.

    Do you work with REST? With Web Service Calls? Did you know those URLs are not statically typed either?

    Have you ever written code based on reflection?

  9. Shahar Y

    Said on November 4, 2008 :

    @ Jonathan Allen

    When working with XML and such, you can check if a tag exist before using it. It is the same with reflection.
    This keyword shall be used only for VERY specific tasks, so I would recommend to declare it only in the Interop namespace…

  10. Jason Kikel

    Said on November 4, 2008 :

    “This feature moves us away from strong typing meaning that many years of wisdom is being thrown out of the window.”

    Ugh, static typing does NOT mean strong typing and dynamic typing does NOT mean weak typing.

    In my opinion, one of the benefits of dynamic languages is that they require you to make use of thorough unit tests (which you should be doing in static languages anyway). The first argument most people make when they have been programming statically all their lives is that you lose all of your type safety and the whole world will fall apart. In my experience this is not even remotely the case. Given you have a disciplined developer base who follow good engineering processes, dynamic typing introduces great productivity along with strong motivation to adhere to good unit testing practices.

    Further, the intellisense comment is only a problem for VS. If you fire up JRuby in NetBeans, you’ll notice full intellisense support.

    So, I’m sorry you feel so strongly about this new addition to C#. I feel it will be a great boon to many developers.

    By the way, C# extension methods are FAR more potentially destructive than the dynamic keyword will ever be. It just comes down once again to the discipline of your developers.

  11. Frank Quednau

    Said on November 4, 2008 :

    Congrats. You are the winner to the “Who will be the first to whine about the dynamic keyword on .NETKicks on the frontpage” contest.
    Mate, if you don’t like it don’t use it. Or use ruby instead.

    Just kidding.

  12. Karl Agius

    Said on November 4, 2008 :

    Features are there to be used *if and when* needed. I don’t see anywhere I’d use these on any project I’m working on right now, but there have been a few times I could have used such a tool in the past. In future? Who knows. Now it’s there, the option is open.

    re. “The problem is that when running our program, we never reach all of the paths so we might never face our problem, our customer will.” – Test. And test hard. I don’t want to sound righteous – and I’m as guilty as many of unit tests with holes in them – but if you *need* to use a feature you’re concerned about, like dynamics, test and mock the hell out of it. Trust me, it goes a long way to improve one’s confidence.

    That said, I’m happier to see someone who’s careful about using new stuff than someone who will use it just because it’s there. Like Will said above – only a moron will do that sort of thing.

  13. lol

    Said on November 5, 2008 :

    I am going to write all of my code, then before I release it will change all of the types to dynamic, just to make all of your lives HELL. Billy said it best… let COM die. You suckers are holding on to the past.

  14. Vijay Santhanam

    Said on November 5, 2008 :

    “With great power, comes great responsibility”

    I love quoting that when people talk about a new technology potentially destroying their worlds.

    use FXCop into your build process and make a rule rejecting the dynamic keyword and you’re solid.

  15. Shahar Y

    Said on November 5, 2008 :

    @ Frank Quednau

    “Mate, if you don’t like it don’t use it”
    Believe me, I won’t (unless I need it for interop). The problem is that we are not working alone and we might “suffer” from others using it…

  16. GD

    Said on November 5, 2008 :

    I agree. It will be abused.

    Something’s wrong with IronPython and/or IronRuby, if you needed this kind of stuff?

    Anyway, too late to complain now. It’s done.

  17. Steve

    Said on November 5, 2008 :

    This is exactly what people said when they first heard about extension methods :P now everyone uses them

  18. Zharfan Mazli

    Said on November 5, 2008 :

    I agreed with you. Good framework/language should not be open for mistakes.

  19. Alex van Beek

    Said on November 5, 2008 :

    I guess you have a problem with “var” also. Just like “var” sometimes NEED to be used (with LINQ), “Dynamic” will have it’s uses.

  20. Tim C

    Said on November 5, 2008 :

    ALL this does is make reflection easier. There is nothing new.

  21. Chris Marisic

    Said on November 5, 2008 :

    The dynamic keyword is a very very powerful addition to .Net, yes it’s scary but I’m glad they are adding it, I believe one of the already clear cut and dry for application of the the dynamic keyword is to rewrite the implementations of dynamic proxies in a much simpler and clearer fashion.


  22. Billy Biro

    Said on November 5, 2008 :

    I used to develop in VB6 (and 5 and 4 etc.etc.)

    To me, introducing the “dynamic” keyword into the C# language is exactly equivalent of VB6’s old “variant” keyword. No typing, loosely bound, free-for-all of a mess.

    If chasing the “functional” programming paradigm means loosely typing everything in the future, then I don’t want it. One of C#’s biggest strong points is that it is a very strongly typed language. Please don’t destroy that now.

  23. Jeff Klawiter

    Said on November 5, 2008 :

    I don’t think the dynamic keyword will be as bad as you think. It’s there to replace .Invoke and other string based reflections. Where ever that’s used people already have to use strings and it gets tested at runtime. All this is doing is make it easier to write the code that already would have had to be checked at runtime.

    I come from a dynamic language background, switched to C# 4 years ago. There are many programmers out there in the world now that are used to runtime binding. It is the very nature of some of the most popular web languages. I love the benefits of statically typed languages but the computer world is not that rigid. Working with COM and dynamic languages is becoming a must.

    As for trusting other programmers, I think we have to trust in people like you that inform them that it’s not a tool to be used for all jobs. It is there for the times you really need it. I’m sure the literature will add all the caveats that this is done at runtime, can increase the risk of bugs. Plus.. any programmer that really abuses it, is working in the wrong language.

    These changes are finally allowing me to gain traction with the dynamic programmers at my company. I, as a C# .NET developer, am in the minority. PHP, Python and Ruby rule the roost here. But the mere fact that we can have 3 of those 4 running together is a big selling point.

  24. Shahar Y

    Said on November 5, 2008 :

    @ Alex van Beek

    The var keyword is not the same at all.
    It is resolved at compile time, unlike the dynamic keyword!

  25. Randolpho

    Said on November 5, 2008 :

    I have never been a big fan of dynamic languages, precisely because static language IDEs grant you such great intellisense. It just makes my programming life easier.

    Until I need dynamicism for some reason, of course. This is almost always because I’m trying to deal with an object for which I have no way of obtaining static compile-time information. The scenarios folks have mentioned here include COM interop, dealing with MS Office, etc, but there are plenty of others. Having the ability to simply call a method you want to call and maybe catch an exception if it doesn’t exist is a heck of a lot easier than the programmatic yoga we normally have to do.

    Will I use it for everyday scenarios? No way.

    What I like most about the dynamic keyword is that it’s explicit. The normal MO is what we’re all used to. It’s only when you explicitly say you’re going dynamic that you suddenly lose all that static greatness in favor of the dynamic easiness.

  26. Gander

    Said on November 5, 2008 :

    You can just as easily “suffer” from any other bad decisions another programmer can make. Just like you can find yourself working with great code that another programmer can write – and guess what, that great code might just happen to include the new “dynamic” *gasp* features of C#. The right tool for the right job. Having static typing doesn’t make anyone a better programmer. It doesn’t make them worse, either, but to suggest that you’re going to suffer from others sounds a lot like tunnel vision to me.

  27. Bart Czernicki

    Said on November 5, 2008 :

    I agree with Ricky…this has been available in VB.NET and I actually used Late Binding for an interface COM assembly I needed to build several years ago…it went a lot quicker than doing it in C#.

    I think in some scenarios this will help like COM interfaces. But to me its like eh for now.

  28. Caleb

    Said on November 6, 2008 :

    If someone keeps on top of the C# language features enough that they know about the “dynamic” keyword then I think they will know why they shouldn’t use it all the time. Allot of people don’t even know about all the language features in C# 2.0 let alone C# 4.0.

  29. RickyAH

    Said on November 6, 2008 :

    Bart, that’s the specific scenario I worked on: binding to a COM interface which was not registered in the system.
    I was using C# but the scarce documentation I had used VB, so it was terrible that in VisualBasic you could do:

    object obj = GetCOMInterface();

    And in C# you needed to do:

    object obj = GetCOMInterface;
    Typo objType = obj.GetType();
    objType.InvokeMember(“parameter1″, BindingMethod.Method, null, obj);

    What the VB compiler really does is just generate all the code necesary for a LateBinding call behind the scenes.

    This is the simplest example, more complex ones are a PAIN e.g:
    – COM interface method which returns ANOTHER COM object:

    VB: obj.GetInterface().PerformSomeAction();

    object obj2 = ot.InvokeMember(“GetInterface”, BindingMethod.Method, null, obj);
    Type obj2Type = obj2.GetType();
    obj2Type.InvokeMember(“PerformSomeAction”, BindingMethod.Method, null, obj);

    And as I have limited time, I won’t talk about parameters by reference, nor invoking indexers o properties…

    I’ve in fact made a small simple library (called LateBindingHelper) that simplifies a little all this mess, but I was (secretly) jealous of VB.NET developers for that specific feature.
    Dinamic keyword is’t a GREAT addition.

    Yes it could be pottentialy dangerours or overused, but that could happend with a lot of currently C#3.0 features. I’ve encounter some projects, like TreeSurgeon, which uses var for declaring every variable: HashTables, strings, every temporally variable in a method, is declared as ‘var’.

    That makes the code impossible to use with C#2.0 and it’s the UNIQUE C#3.0 feature it has. Is used only to save typing.
    I’ve replaced every var-declared variable with the proper type and voila! now it has become C#2.0 complaint…

  30. NinjaCross

    Said on November 7, 2008 :

    I totally agree with your point of view, Shahar Y.
    Dynamic lookup is totally an awesome feature from a purely academic perspective, but IMHO is really too much human-error-prone.
    The fact is that programming paradigms must (and not only could) impose some well-define (black or white) constraints on programming behaviours, and this seems to me a “gray” feature that in a real world context would drive many programmers implementing weak or poorly designed architectures.

  31. Buu Nguyen

    Said on November 14, 2008 :

    Well, hardly anybody would use dynamic for such scenarios when the static type is known at compile time.

    Dynamic lookup is useful when you have to interop with objects coming from dynamic languages like JavaScript, IronPython, which obviously have no static type. Also in many cases when you need to use reflection (you do use reflection, don’t you?), dynamic would make the code look less verbose.

    I discuss about this (and the benefit of other features of C# 4.0) more thoroughly in my post: http://www.buunguyen.net/blog/new-features-of-csharp-4.html

  32. Kerem Kusmezer

    Said on November 14, 2008 :

    First of All : (The dynamic keyword is a very very powerful addition to .Net)
    VB.Net can already do that since version VB.Net 7.0.
    Option Strict Off.
    If you are doing heavy Com Interop and if you won’t use PIA it is really usefull, but this new dynamic language paradigm stuff ( which for me is old dinner coming back again ) because we already had vbscript. :)
    I think 2 year cycle is to fast for a programming language to be changed dramatically, which in case of C# 3.0 , most of the features are syntatic sugar. Automatic properties etc.

  33. Carlos

    Said on November 26, 2008 :

    Ppl. are usually afraid of what they don’t understand. The thing is that this feature comes to aid interop with not only COM stuff but also dynamic-typed languages. The problem with dot net developers (and I include myself into that group) is that they can’t see outside of their long-loved environment. And outside there are exciting things going on like RoR, CouchDB, Erlang etc. and as always Microsoft (and microsofties) must be carried kicking and screaming into the next paradigm. See F#? That’s functional programming done wrong. Just ask some more enlightened microsoft guy like Erik Meijer.

    Anyway… if that wasn’t enough, it’s often easy to spot a bad programmer. If you’re afraid your code will break at runtime, that’s because you don’t test enough. Your code coverage is slim to none and you rely way too much on a compiler that’s not even intelligent enough (yet!) to figure out things like contracts. Ruby programmers are not afraid of their code because they do test properly. Bottom line is: things on the other side of the fence are getting done, getting delivered and yet we have a bunch of bad programmers on this side whining about new features when they should be demanding the proper implementation of them. Sorry to be so sincere, but for a guy whose blog is so well ranked in google, you should really get your act together before commenting on a feature you obviously don’t understand.

  34. hyperspaced

    Said on December 8, 2008 :

    Is it dynamic that bothers you or the fact that such a keyword is introduced to C# 4.0 (that is: four-point-zero) in the year 2009 ?

    COM interop? Hellooo, have you been living inside a cave for the last 10 years people?

    OK, suppose there are some guys out there needing it. Morons are always morons as Will (the first post) said, so they don’t need ‘dynamic’ to f*ck things up. It’s always nice to have an extra tool, but… IN C# 4.0? IN THE AGE OF 32nm PROCESSORS? What about optional parameters and named arguments? In 2009 too?

    I am VERY dissapointed with the feature set of C# 4.0. C# 4.0 tagline should be ‘MULTICORE and PARALLEL PROGRAMMING’, not ..dynamics!!

    I am not pleased with Anders presentation/lecture on PDC 2008 either: He mentioned ‘Concurrency’ as the next big thing, but he devoted all his time in dynamics (he quicky said a sentence about the ‘.NET parallel extentions’, nearly not as nuch time required for the ‘next big thing’)!!!

    So, then next time I will be programming .NET 4.0 applications on my clients’ Core Duo’s or Core i7’s, I will have in mind to use dynamic wisely.

  35. Hervé

    Said on December 14, 2008 :

    I really think that adding this dynamic keyword is a BIG mistake. C# is a static language, adding this keyword will not make it dynamic, but it will also cease to be static. There’s something Microsoft should have learned: A good (x = application, software, library) is not an that does everything you might think of in the world (even crazy things), it’s a that is clear about what it does (so you know what to expect), and does it well. Judging on the rate on which Microsoft adds “the next cool feature” in C#, I’m not sure that C# belongs in this category anymore. Simplifying COM interop ? Why adding a keyword and a core language feature for that ?

  36. Saw

    Said on January 23, 2009 :

    2009 is not a good year.

    The global economy continue going down; and C# add in “dynamic” to its version 4.0

    “dynamic” is bad, not because how it should work, but because I still can’t make it as my programming weapon, yet. It may never will be as well, as, frank, I don’t have any working experience on COM interop, nor that do I use reflection heavily.

    “dynamic”, like “var”, can causes a lot of ‘problem’ if not use properly. I still in the progress to make “var” as my weapon in the resume, and now, “dynamic” come out.

    Although I can’t see any usage of “dynamic” in my current job yet, but I do learn something from “var”. That is: stick to the initial purpose why “var” was created. I believe it would be same as “dynamic”.

    That’s it. My 2cent. I going for learning now.

  37. Tobias Manthey

    Said on February 4, 2009 :

    Even today you can do dynamic programming in .NET. It’s even called DynamicMethod (System.Reflection.Emit) today.

    Strong typed or not. There is no protection from crap code. Face it.

    The problem with the compile time library references greatly reduces the usability .NET and its about time to give it up. Ask all the developers using the Office COM objects. And you are not telling me that software around Office is an insignificant purpose.

    We won’t see much use though as Intellisense will obviously fail here.

  38. Phyx

    Said on April 22, 2009 :

    I sincerely hope this can’t be used with normal code, that much like unsafe code you need to wrap it in unsafe blocks and turn on a compiler flag.

    This is the worse decision ever, my entire problem with this is, people will abuse it to create horrific code. Also I’d like to reply to what three people said above:

    someone said that it’s a great thing, look at python and ruby etc, well the reason i use C# is because i’m pretty much against dynamically types languages such as python and ruby. I’m very pro static typing. I like to do static check.

    someone also said that it’s a vs issue that intellisense no longer works. By nature the compiler has no information about the dynamicallly types variable at design or compile time. You statements about other IDEs being able to do intellisense on this is making me think you don’t even know what dynamic typing is.

  39. Phyx

    Said on April 22, 2009 :

    I sincerely hope this can’t be used with normal code, that much like unsafe code you need to wrap it in unsafe blocks and turn on a compiler flag. I hope they introduce enough restrictions that it can’t be abused. (but i really don’t see them doing this)

    This is the worse decision ever, my entire problem with this is, people will abuse it to create horrific code. Also I’d like to reply to what three people said above:

    someone said that it’s a great thing, look at python and ruby etc, well the reason i use C# is because i’m pretty much against dynamically types languages such as python and ruby. I’m very pro static typing. I like to do static check.

    And also someone said don’t use it if you don’t like it. I wish it were that simple. When working on a team project, if someone uses it you’re stuck with it. So even if you don’t want to use it, you’re stuck with it.

    someone also said that it’s a vs issue that intellisense no longer works. By nature the compiler has no information about the dynamicallly types variable at design or compile time. You statements about other IDEs being able to do intellisense on this is making me think you don’t even know what dynamic typing is.

  40. Alex van Beek

    Said on May 12, 2009 :

    I know that var is not the same as dymamic :) I’m just pointing out that at first people also had a lot of problems with var, but time proofed that it has its uses. Just like with var, time will proof that dynamic has its uses, especially with COM interop.

  41. kerem kusmezer

    Said on May 13, 2009 :

    Well , but please put a switch to the compiler so i can at least shut it down or force not to use it, like allow unsafe code switch etc.

  42. pavel

    Said on August 23, 2009 :

    Very good suggestion (from Kerem) to have a switch to the compiler similar to “unsafe” code.. being a VB6 and classic ASP veteran who moved to C# (and asp.net) when it was still in beta (and never looked back) i don’t understand why MS is turning a beautiful language like C# into VB or javascript alikes!
    Dynamics might be useful in a very few scenarios but in most cases must not be used.
    Just imagine maintaining the code written by someone whom you never saw a couple of years ago that uses dynamics all throughout. urghh.. a scary thought.

    ah, optional params.. why not just create overload method..

  43. stranger

    Said on November 5, 2009 :

    I think c# must keep up with the features of the DLR.
    For the most part, I don’t think dynamic programming is a good idea, but if used carefully, it can make some things easier.

  44. SKid

    Said on November 30, 2011 :


    I returned after several years to C#. Well, I just fell into a pit here and have absolute no chance to solve it, because the documentation is simply wrong, or not, or whatever… the doc of a lib, I am using, specifies a method that returns a dynamic type. within that dynamic type, I should call a method called “Close”. Well, that simply doesn’t work. I have absolutely no idea why! And that is the problem, I will have to DISASSEMBLE that lib now! Yes, it could lead to hard core debugging for i386… well, has somebody the good old ICE?

    Well, this is an absolute show stopper for me! Jesus! No discussion! Never! I have never seen such obvious brainless feature really causing arm.

    @Shahar: If you are still using C#: Yes I totally agree with you! Some years later, yes, but I think, this is valid for the next 10000 years, I am sure.

    I will migrate to different things now. C# is dead for me! Sorry, but that’s a no-go!

Post a Comment