Fun With Method Missing and C# 4

asp.net, code, asp.net mvc 0 comments suggest edit

UPDATE: Looks like the CLR already has something similar to what I did here. Meet the latest class with a superhero sounding name, ExpandoObject

Warning: What I’m about to show you is quite possibly an abuse of the C# language. Then again, maybe it’s not. ;) You’ve been warned.

Ruby has a neat feature that allows you to hook into method calls for which the method is not defined. In such cases, Ruby will call a method on your class named method_missing. I showed an example of this using IronRuby a while back when I wrote about monkey patching CLR objects.

Typically, this sort of wild chicanery is safely contained within the world of those wild and crazy dynamic language aficionados, far away from the peaceful waters of those who prefer statically typed languages.

Until now suckas! (cue heart pounding rock music with a fast beat)

C# 4 introduces the new dynamic keyword which adds dynamic capabilities to the once staid and statically typed language. Don’t be afraid, nobody is going to force you to use this (except maybe me). In fact, I believe the original purpose of this feature is to make COM interoperability much easier. But phooey on the intention of this feature, I want to have some fun!

I figured I’d try and implement something similar to method_missing.

The first toy I wrote is a simple dynamic dictionary which uses property accessors as the means of adding and retrieving values from the dictionary by using the property name as the key. Here’s an example of the usage:

static void Main(string[] args) {
  dynamic dict = new DynamicDictionary();

  dict.Foo = "Some Value";  // Compare to dict["Foo"] = "Some Value";
  dict.Bar = 123;           // Compare to dict["Bar"] = 123;
    
  Console.WriteLine("Foo: {0}, Bar: {1}", dict.Foo, dict.Bar);
  Console.ReadLine();
}

That’s kind of neat, and the code is very simple. To make a dynamic object, you have the choice of either implementing the IDynamicMetaObjectProvider interface or simply deriving from DynamicObject. I chose this second approach in this case because it was less work. Here’s the code.

public class DynamicDictionary : DynamicObject {
  Dictionary<string, object> 
    _dictionary = new Dictionary<string, object>();

  public override bool TrySetMember(SetMemberBinder binder, object value) {
    _dictionary[binder.Name] = value;
    return true;
  }

  public override bool TryGetMember(GetMemberBinder binder, 
      out object result) {
    return _dictionary.TryGetValue(binder.Name, out result);
  }
}

All I’m doing here is overriding the TrySetMember method which is invoked when attempting to set a field to a value on a dynamic object. I can grab the name of the field and use that as the key to my dictionary. I also override TryGetMember to grab values from the dictionary. It’s really simple.

One thing to note, in Ruby, there really aren’t properties and methods. Everything is a method, hence you only have to worry about method_missing. There’s no field_missing method, for example. With C# there is a difference, which is why there’s another method you can override, TryInvokeMember, to handle dynamic method calls.

What havoc can we wreack with MVC?

So I have this shiny new hammer in my hand, let’s go looking for some nails!

While I’m a fan of using strongly typed view data with ASP.NET MVC, I sometimes like to toss some ancillary data in the ViewDataDictionary. Of course, doing so adds to syntactic overhead that I’d love to reduce. Here’s what we have today.

// store in ViewData
ViewData["Message"] = "Hello World";

// pull out of view data
<%= Html.Encode(ViewData["Message"]) %>

Sounds like a job for dynamic dictionary!

Before I show you the code, let me show you the end result first. I created a new property for Controller and for ViewPage called Data instead of ViewData (just to keep it short and because I didn’t want to call it VD).

Here’s the controller code.

public ActionResult Index() {
    Data.Message = "<cool>Welcome to ASP.NET MVC!</cool> (encoded)";
    Data.Body = "<strong>This is not encoded</strong>.";
    
    return View();
}

Note that Message and Body are not actually properties of Data. They are keys to the dictionary via the power of the dynamic keyword. This is equivalent to setting ViewData["Message"] = "<cool>…</cool>".

In the view, I created my own convention where all access to the Data object will be html encoded unless you use an underscore.

<asp:Content ContentPlaceHolderID="MainContent" runat="server">
 <h2><%= Data.Message %></h2>
  <p>
    <%= Data._Body %>
  </p>
</asp:Content>

Keep in mind that Data.Message here is equivalent to ViewData["Message"].

Here’s a screenshot of the end result.

dynamic-mvc

Here’s how I did it. I started by writing a new DynamicViewData class.

public class DynamicViewData : DynamicObject {
  public DynamicViewData(ViewDataDictionary viewData) {
    _viewData = viewData;
  }
  private ViewDataDictionary _viewData;

  public override bool TrySetMember(SetMemberBinder binder, object value) {
    _viewData[binder.Name] = value;
      return true;
  }

  public override bool TryGetMember(GetMemberBinder binder,
      out object result) {
    string key = binder.Name;
    bool encoded = true;
    if (key.StartsWith("_")) {
      key = key.Substring(1);
      encoded = false;
    }
    result = _viewData.Eval(key);
     if (encoded) {
       result = System.Web.HttpUtility.HtmlEncode(result.ToString());
     }
     return true;
  }
}

If you look closely, you’ll notice I’m doing a bit of transformation within the body of TryGetMember. This is where I create my convention for not html encoding the content when the property name starts with underscore. I then strip off the underscore before trying to get the value from the database.

The next step was to create my own DynamicController

public class DynamicController : Controller {
  public dynamic Data {
    get {
      _viewData = _viewData ?? new DynamicViewData(ViewData);
      return _viewData;
    }
  }
  dynamic _viewData = null;
}

and DynamicViewPage, both of which makes use of this new type.

public class DynamicViewPage : ViewPage {
  public dynamic Data {
    get {
      _viewData = _viewData ?? new DynamicViewData(ViewData);
      return _viewData;
    }
  }
  dynamic _viewData = null;
}

In the Views directory, I updated the web.config file to make DynamicViewPage be the default base class for views instead of ViewPage. You can make this change by setting the pageBaseType attribute of the <pages> element (I talked about this a bit in my post on putting your views on a diet).

I hope you found this to be a fun romp through a new language feature of C#. I imagine many will find this to be an abuse of the language (language abuser!) while others might see other potential uses in this technique. Happy coding!

Tags: dynamic, aspnetmvc, C#, DLR

Found a typo or error? Suggest an edit! If accepted, your contribution is listed automatically here.

Comments

avatar

59 responses

  1. Avatar for Nikhil Kothari
    Nikhil Kothari August 26th, 2009

    Very cool...
    I am a fan of using dynamic in c# 4 to clean up various common usage patterns, where you're anyway doing late-bound string-based programming, just with an unnatural syntax.
    Of course, I am sure you'll have no shortage of finding people who will be quick to point to the perils and the abuse factor. I had the same experience when I did my c# 4 dynamic and making REST API calls post :-)

  2. Avatar for Cengiz Han
    Cengiz Han August 26th, 2009

    cool and useful!
    Same thing can be implemented using RealProxy in C# earlier versions.
    msdn.microsoft.com/.../...g.proxies.realproxy.aspx
    But using dynamic type has no mess. very simple.
    thanks.

  3. Avatar for Daniel Wiedenhofer
    Daniel Wiedenhofer August 26th, 2009

    hi,
    that sounds great, but in my opinion in large mvc-appliactions there is no way of using neither viewdatadictionary nor viewdata as dynamic object - the only way are strongly typed viewdata objects for each view, so you can easily recocnize which data is available in views.

  4. Avatar for Stephane
    Stephane August 26th, 2009

    Hehe very fun coding indeed. Language abuse or not, this makes the code cleaner from the outside :). hiding some more magic under a convention inside your DynamicViewPage. Isn't "Convention over Configuration" a rule of ASP.NET MVC? :)

  5. Avatar for Dummy Customer
    Dummy Customer August 26th, 2009

    "Lord Gates, The Dark Force is strong in apprentice Haack. Soon he will annihilate all that is static in the force. The Jedi are Doomed!"
    Good example on the use of dynamic.
    BUT I am never ever going to use it. I have been bitten too much by dynamic languages to ever get back to using them. The problems are too many to count: Variables popping into existing from nowhere, methods that were missing, hard to track typos in methods/variables, shitty performance, hellish debugging.....the horror.....the horror!
    I need something like: Option Strict in my code so to prevent a project from compiling if it has dynamic anywhere in it.

  6. Avatar for Dummy Customer
    Dummy Customer August 26th, 2009

    @Daniel Wiedenhofer
    +10 points. I agree!

  7. Avatar for slugster
    slugster August 26th, 2009

    Mmmmm... so i can make my C# objects behave like javascript objects - i can think of no reason why i would *want* to do this. Nor do i really want consumers of my data objects to just add properties using the dynamic method, not when they can just inherit from my object and extend it in the regular OO way.
    Surely there has to be more uses for this than just interop with dynamic languages?

  8. Avatar for Steve Willcock
    Steve Willcock August 26th, 2009

    Looks interesting, I wonder what sort of perfomance impact this would have in a real world application? By the way, I should point out that you don't normally wreck havoc, you wreak it instead, although I suppose you're entitled to do either if you see fit :)

  9. Avatar for Adam
    Adam August 26th, 2009

    Very cool Haackage there! I like. However, now my convention that the View to be rendered is determined by the name of the strongly typed viewmodel class passed to the view will not work.
    eg. return View(new IndexHomeViewModel {}); will render the IndexHome view.
    Kudos for extending the boundaries though!

  10. Avatar for Jeffrey Becker
    Jeffrey Becker August 26th, 2009

    This is definitely a very cool concept. My experience is that this really has the biggest impact on code that is very verbose to write manually and easily inferable from an api. COM interop, GUI toolkit bindings & Data Access are the 3 biggest places I remember seeing it way back in the perl days.
    I don't personally find the "but I don't get static type checking" argument compelling. Most of the problems cited with not having the compiler check stuff for you are easily solved as a side-effect of writing the unit tests you need to write to make sure that things work.
    @Steve: No doubt the example here is slower than simply accessing the dictionary. Most of the time you're using dynamic objects to abstract away large amounts of code that is going to be orders of magnitude slower than the penalty you pay for a dynamic api.

  11. Avatar for Nevada
    Nevada August 26th, 2009

    Interesting post. I lean more toward statically typed programming myself as several posters have already mentioned.
    I do appreciate the tone of the post though. Playful and fun instead of stodgy and institutional. I wish more people posted in a similar manner.
    Programming is supposed to be fun after all!

  12. Avatar for zvolkov
    zvolkov August 26th, 2009

    Can't abuse feature that was designed to do exactly what you're doing here! Irrelevant of this particular example, the drive towards DSLization is the right one and dynamic method resolution can help C# APIs get on board of that train.

  13. Avatar for Phillip
    Phillip August 26th, 2009

    Sigh... I hate the idea of dynamic properties and named properties in C#. Now there's Dynamic Methods? Yuck. Almost makes me want to pick up a new language and leave .net

  14. Avatar for LOL @ Phillip
    LOL @ Phillip August 26th, 2009

    Leave .NET because of a language feature THAT YOU DO NOT HAVE TO USE?! Get a grip. It just means that for more people the C# peg is fitting more holes.
    That is a lame metaphor :-(

  15. Avatar for notsure
    notsure August 26th, 2009

    if I go to c# is not so i try to mimic what other languages do, again like in other posts, as an ex linux java person the more i realize about c# and .net the more i crave to go back since c# is now like you started the article, copying the good features of other languages, can .net really stand up and actually be a leader by not copying things like this but really analysing the problems at hand and inventing new techniques ? if i need this then i go back to php, which had this feature back in 2000 , are we catching up or what ?

  16. Avatar for Stuart B
    Stuart B August 26th, 2009

    Awesome! I'll definitely be using this when we pick up C# 4.0. This is perfect for views, where I don't want to clutter everything up with (casts).
    I'm not that familiar with the dynamic features of C# overall. How does this perform? I'd assume there is some overhead, but will it noticably affect me?

  17. Avatar for DonSleza4e
    DonSleza4e August 26th, 2009

    Just integrated into my MVC project :D
    Thanks!

  18. Avatar for Mohammad Azam
    Mohammad Azam August 26th, 2009

    Hi,
    Dynamic keyword is a great addition in the .NET 4.0 but I think using it in this way makes is hard to be discoverable. I have used dynamic keyword in the scenarios where IronRuby is returning a ruby object from the DLR and .NET is catching that object using the dynamic keyword.
    www.highoncoding.com/.../...k_at_the_IronRuby.aspx
    Thanks,
    Azam

  19. Avatar for Tim
    Tim August 26th, 2009

    Grammer problem with "What havoc can we wreck with MVC?":
    www.dailywritingtips.com/wreck-wreak-and-other-...

  20. Avatar for DF
    DF August 26th, 2009

    @Tim: Pointing out a grammar mistake while making a spelling error- the comedy!
    http://dictionary.reference.com/browse/grammar

  21. Avatar for Steve G
    Steve G August 26th, 2009

    Q for Phil: Is there some way to combine Generics with this technique to help with compile time type checking?
    Something like (to my feeble mind):
    public override bool TrySetMember(SetMemberBinder binder, <T>value)
    and
    public override bool TryGetMember(GetMemberBinder binder,
    out <T>result)

  22. Avatar for Aaron Erickson
    Aaron Erickson August 27th, 2009

    I can see this as being immediately useful in things like Fit tests. I frequently have a need to convert tests expressed by business users (imagine, someGroup.someProperty) into dictionary lookups. Having something like this makes it much easier for me to allow business users who help us write acceptance tests to do so in a much more natural way.
    Thanks for this!

  23. Avatar for John Meyer
    John Meyer August 27th, 2009

    Abuse? It hasn't even shipped yet, so how could it possibly be abused? You're just experimenting with pre-release stuff, that's all!

  24. Avatar for Haacked
    Haacked August 27th, 2009

    Thanks for the comments everyone. I corrected the spelling error. :)
    @Steve, you could probably write your own method in the derived class, but keep in mind, Generics are statically typed at compile time, but this is a runtime feature and the value could be any type.

  25. Avatar for Louis DeJardin
    Louis DeJardin August 27th, 2009

    Cool! Now all you need to do is change the base type of ViewDataDictionary to DynamicObject :)

    Phil: We meet again, at last. The DLR is now complete; now I am the master.
    ViewDataDictionary: Only a master of evil, Phil.
    Phil: Your powers are weak, old class.
    ViewDataDictionary: You can't win, Phil. If you change my base class, I shall become more powerful than you can possibly imagine.
    Phil: *slice* *run tests* *commit*

  26. Avatar for Louis DeJardin
    Louis DeJardin August 27th, 2009

    Wait! I must correct myself. I'm not sure if such a type could be used in a way that has the benefits of a dynamic object in addition to the actual properties and strong typing of a typed object.
    In other words I'm assuming you can't have "ViewDataDictionary ViewData" and have the compiler fall back to using a DLR expression for a missing member because it knows the base class is DynamicObject? And you can't have "dynamic ViewData" without losing intellisense and direct compile-time member access and breaking lots of places where it's value is used as a known type.
    Maybe for C# 4.5 parameterize the dynamic keyword if you want to use like "dynamic&lt;ViewDataDictionary&gt; ViewData" or "Dynamic&lt;ViewDataDictionary&gt; ViewData" to imply the use of DLR expressions above and beyond what is known to exist on the CLR type descended from DynamicObject?

  27. Avatar for Bertrand Le Roy
    Bertrand Le Roy August 27th, 2009

    Don't listen to the abuse fearers! This is a great use of dynamic. You are replacing a late-bound, ugly syntax with a late-bound, beautiful syntax. What can possibly be wrong with that?
    The same pitfalls that existed before still exist, but it's easier on the eyes. The only problem I'd see is that it makes it *seem* safer but who cares really? I don't.
    That makes me miss JavaScript on the server a little less. I'd definitely use that.

  28. Avatar for Haacked
    Haacked August 27th, 2009

    @Louis exactly. I thought about that but it would need some new enhancements like what you proposed.

  29. Avatar for Vijay Santhanam
    Vijay Santhanam August 27th, 2009

    nice! I'm with Bertrand- it's rad, but it is dangerous.
    Maybe dynamic objects and their dynamic calls should be coloured differently from statically typed stuff?
    That way anybody can see it's a different situation

  30. Avatar for Eyston
    Eyston August 27th, 2009

    I am struggling with why views are to be statically typed. For simple cases where the view and entity are 1:1, then it doesn't matter. For other cases it seems like building ViewModels in the controller just to pass to the view is a lot of brainless work.
    For example, if I want to have a create shipment view that shows the empty shipment, with a list of customer addresses, a list of all freight carriers, etc... I'd like to just:
    var shipment = order.CreateShipment(); // or whatever...
    var addresses = order.Customer.ShipToAddresses;
    var carriers = carrierRepository.GetAllCarriers();
    return View(new { Shipment = shipment, Addresses = addresses, Carriers = carriers));
    Is this something dynamic will allow in future of MVC? Or is this really stupid? Or can you do this right now and I'm really stupid?
    Also, I think maybe some complaints with this and dynamic is that it is hard for me to test rendering that view without firing up selenium/watin, or can I do this from a unit test somehow (just to ensure the view renders, not to test that it is 'right')?
    I like static typing in my model, but view just seems like a lot of work to make up for lack of tests.

  31. Avatar for DoNotWant
    DoNotWant August 27th, 2009

    Personally, I don't like it.
    I understand why it's there, and for COM interop, something like this needed to be added to C#, but it's been added as a "general purpose" feature that WILL be abused.
    At the risk of starting a flame war, it's so-called "features" like this that made lots of decent VB.NET developers switch to C#. To get away from the "features" that allow you to be exceptionally sloppy in your coding.
    Everyone is saying, "But you don't HAVE to use this feature". But it WILL get used and abused in the real world when deadlines loom and code gets rushed in the name of "getting it out of the door". It's the "other guys" who end up maintaining code written like this that get to deal with the "flexibility" of a dynamic keyword sprinkled all over a code base when correct and proper engineering discipline would dictate that strongly-typed classes/objcets be used instead.
    Just as you don't HAVE to use VB.NET's "features" (most in the name of backwards-compatibility) that promote sloppyness and corner-cutting in your code, for every 1 VB.NET coder that DOES do things "properly", there's 100 that DON'T.

  32. Avatar for Mahmoud Moravej
    Mahmoud Moravej August 27th, 2009

    That was really cool!...I'm not sure whether it is an abuse or not but I don't think so. When we hardcode XXX["stringName"] in our codes, we can normally use XXX.stringName instead...isn't it?

  33. Avatar for Anthony Gatlin
    Anthony Gatlin August 28th, 2009

    Awesome! The C# and ASP.NET teams keep coming up with fabulous new features that reduce the amount of code I have to write. I am sure I will make great use of this fabulous feature. Thanks for previewing it.

  34. Avatar for JC Grubbs
    JC Grubbs August 30th, 2009

    Stick that in your pipe and smoke it Ruby :) The 'dynamic' keyword and it's implementation is absolutely the single feature that keeps me drooling for C#4. Unfortunately, it's also a feature that scares the crap out of me...the average .NET dev will either misuse it (which will be bad) or won't use it at all (which is sad).

  35. Avatar for awwykle
    awwykle August 30th, 2009

    I saw someone comment on the VB "features" which are commonly misused. I assume that what is meant here are the features Option Explicit Off, Option Infer On, and Option Strict Off. As a VB developer, I will readily admit that these three settings together do tend to encourage sloppy coding. I personally set Explicit and Strict On at project level in every one of my projects. I find that Infer is useful in that, for example, I can write a LINQ query and keep adjusting it until I get the type I need (which is shown by intellisense when I hover its variable). I then make a habit of explicitly declaring the type. Having said all this, however, I, like some of the others above, have found that I miss the ability to add "expando" properties to objects under certain circumstances. Does Dynamic make it into VB 4? Also, Kudos on the example. I do not use C# because I don't much like the C++ style of syntax (also why I choose not to use much JavaScript and why I don't use Java), but my understanding is that each language (VB and C#) is supposed to gain features of the other until they are matched and versioned in lock-step...

  36. Avatar for Rusty Zarse
    Rusty Zarse September 1st, 2009

    This is all very interesting.... So many of you get so angry because Microsoft decides to loosen the chain and let you DO something. You do not have to use it. I can't tell you how many times I've wanted to do something completely rational yet the strong typedness of the CLR got in my way. Mocking clas properties that aren't marked virtual, for example. No, this doesn't address that problem, but its a tool. Its something that competes with languages like Python and Ruby that are incredibly powerful in their own way.

    Mostly, though, Ruby is a pleasure to write (or so I hear over and over and over and...). I LOVE c# syntax and I love programming in dot net. So much that my Ruby exploration has taken 4 years and I am still just a Ruby wannabe novice. This feature does two remarkable things: 1) it allows me to write code that might otherwise be impossible and force me to use a dynamic language (IronRuby, perhaps)

    and 2) it provides me with yet another shortcut that I can use when time to market is more important than whether I can check boxes next to some list of proper code commandments.

    I appreciate the innovations that Microsoft has been delivering that allow me to do what I need to do to succeed in business and keep my job rather than have to adhere to strict static type dogma and sit in my mother's basement writing scores of correct code.


    Stop pretending like placing restrictions on what you can do is a good thing.

  37. Avatar for Chance
    Chance September 2nd, 2009

    @notsure "if I go to c# is not so i try to mimic what other languages do, again like in other posts, as an ex linux java person the more i realize about c# and .net the more i crave to go back since c# is now like you started the article, copying the good features of other languages, can .net really stand up and actually be a leader by not copying things like this but really analysing the problems at hand and inventing new techniques "
    Not to insult, but that was the longest sentence I've ever read.
    .Net isn't "copying" other languages, its evolving into something new. What other language or framework does what .Net does? Oh, there isn't one? Okay then.

  38. Avatar for Daniel
    Daniel September 3rd, 2009

    I think I come down on rob's side on this. I've had some doubts ever since I first heard about the dynamic keyword. Static typing made sense, var was cool, and then dynamic comes along, and says maybe static typing isn't as big a deal. In my mind, this breaks some pretty ingrained concepts in development like 'fail fast' and preferring compile-time errors over runtime. In the example you give, it gets rid of 'magic strings', but not really - your app will still compile and run if you misspell 'data.Massage'. But I kind of assumed other people smarter than me knew better. I still somewhat assume that, but it will be interesting to watch play out.

  39. Avatar for Jeffrey Becker
    Jeffrey Becker September 3rd, 2009

    Personally, I'm thrilled to see this feature. My experience has been that dispatch interception is at its most powerful when it replaces code generation. Any place where you have a context and a straight forward set of actions to be preformed based on the context, method-name and parameters is going to be a prime candidate. Off the top of my head the best usages I remember from my perl days were: COM interop, GUI toolkit bindings (this is how the TK bindings worked), and DB access. I assume it would be good for a scaffolding framework too.
    That said, there are very mature technologies for all those things which already exist in the .Net space. I don't personally intend to reinvent any of those wheels at the moment.

  40. Avatar for Joe Chung
    Joe Chung September 3rd, 2009

    It's weird how if you use dynamic to implement something like this, the static type police will cry foul, but if someone were to use T4 code templates or some other code-gen to do the same thing, it's all copacetic.

  41. Avatar for E Rolnicki
    E Rolnicki September 3rd, 2009

    "just to keep it short and because I didn’t want to call it VD"
    LOL.

  42. Avatar for George Mauer
    George Mauer September 3rd, 2009

    Or even better.
    dynamicDictionary.Output = x => Console.Writeline(x);
    dynamicDictionary.Output(x);

  43. Avatar for Daniel
    Daniel September 3rd, 2009

    @joe - the difference between using T4MVC to do similar and using dynamic in the way Phil suggests is that in the T4MVC approach, you get compile time errors telling you that you've misspelled something or a name has changed. With this dynamic approach, you'll never notice until a customer calls and says "why do I never see a message", you dig through code, and find that you misspelled it. Even Phil seems to acknowledge this with the warning at the top of this post. So yeah, T4MVC is copacetic precisely because you get the benefit of this dynamic thing, you don't have to write code for it to work, and you get compile-time checking and intellisense.

  44. Avatar for Tomas  Jecha
    Tomas Jecha September 6th, 2009

    this is quite scary stuff for me. Where is that good old fashion C# without all mutations like this? I would like to see C# in 10 years. It's getting harder and harderto teach.

  45. Avatar for Bertrand Le Roy
    Bertrand Le Roy September 9th, 2009

    Quick question: why implement your own DynamicDictionary whereas ExpandoObject is pretty much it already?

  46. Avatar for Prodis
    Prodis September 10th, 2009

    You are a crazy man! Great job! Congratulations!

  47. Avatar for MR A
    MR A September 10th, 2009

    Why not just use a "proper" dynamic language instead on the CLR or DLR?
    Lots of fun with Python to be had, nice short code. Beware though there be Dragons here!
    Even Better, bite the bullet do Haskell. The one language in the world that makes me feel that I am stupid. Monads, Monoids!

  48. Avatar for Dynamic Big boy pants
    Dynamic Big boy pants September 10th, 2009

    To wrap up the problem with Dynamic languages.
    Are you a Brick, no ok are you a house, no ok, were you in Jaws no, ok, do you live in LA, no ok......etc
    you end up asking so many questions to verify if something is what it should be that you hit performance issues.
    I like F#'s way.

  49. Avatar for Dynamic Big boy pants
    Dynamic Big boy pants September 10th, 2009

    Bit more thought.
    Dynamic suggests that everything is a Dog if it goes woof. Well Like the joke says, you can make a cat go woof by setting it alight. But whats the use of dead Cat that should have been a dog that is burnt to a crisp just because you want to make something do a really cool thing that its "not suppose to do". Yes we can all break rules but the rules are there for a reason. In the case of the cat, we all love cats and don't want to set them alight. you get my drift.
    It really comes down to good programming form. There is nothing new that Dynamic really introduces to the CLR that you couldn't do since CLR 1.0. All the dynamic stuff does is make it easier. I mean there has always been Dynamic Invocation on code written on the fly, what the difference really. If you really scared you could always bung the code into a brand new appDomain, and unload it if it gets too scary for your main app.
    The Dynamic stuff will however make companies like ours change the policy of languages used. It would be nice to have a big switch to say "nope, no funny stuff here if you please mr Graduate programmer who wants to impress me with his powerful syntax". This would allow the abuse to be done by people who know what they are doing and know the consequences, instead of the "oh no, new boy has done some dynamic crap here, lets go back to beta and remove it" approach.

  50. Avatar for Mark Lindell
    Mark Lindell September 11th, 2009

    Count how many times the word "Cool" appeared on this page. Cool doesn't make my code easier to troubleshoot or my deliver business features faster. IMHO these features should be limited to COM interop and framework developers.

  51. Avatar for graffic
    graffic September 16th, 2009

    This feature was present in other languages years ago. It has been in production applications using these languages. This feature also breaks the "static typing".
    So you like non static typing, you love features from other non static typing languages. Question. If you mod your car like (for example) a VW Golf: wheels, door, interior. Why don't you buy a golf? <- Now apply this to C#.
    You will loose this:
    stackoverflow.com/.../why-is-c-statically-typed
    I like the feature, but I see that C# is becoming a mix of everything. Without being the best at many things.

  52. Avatar for anirudha gupta
    anirudha gupta October 11th, 2009

    hello haccked before some day i install VS 2010 Beta from official site but when we worked on VS 2010 he was hang and closed automatically And i not see any error for it's closed problem
    so how to use VS 2010 Fast.
    give me answer to our id & Solve Bug in Vs 2010

  53. Avatar for Quiz
    Quiz October 14th, 2009

    public dynamic Data {
    get {
    return _viewData ?? (_viewData = new DynamicViewData(ViewData));
    }
    }
    :)

  54. Avatar for hearse for sale
    hearse for sale December 17th, 2009

    I really need to work on programming..this is beyond me.

  55. Avatar for Jacob
    Jacob July 20th, 2010

    Hey, static morons, maybe you didn't notice, but this code a wrapper for an Object Dictionary that has string parameters.
    Making it dynamic doesn't actually lose any type-safety or intellisense because it never had any.

  56. Avatar for Magellan
    Magellan July 26th, 2010

    First, use language, do not misuse it!
    Second, use proper tools (in our case classes), don't do "ma' look what I made!"
    Third and most important, think about team members, if you are about to do something, ask them, maybe they are lazy to learn!
    My point is, if you need to create something, make it inexpensive and with good quality. If you don't need DLR than do not use it. Also, play for a while with tools, try to do things, just to see how useful it can be or not.

  57. Avatar for Alex
    Alex January 3rd, 2011

    How is this close to the method_missing in ruby? I dont see the relation

  58. Avatar for Fast torrent download
    Fast torrent download January 25th, 2011

    I'll definitely be using this when we pick up C# 4.0. This is perfect for views, where I don't want to clutter everything up with (casts).

  59. Avatar for
    January 10th, 2012

    I don't have a problem with the keyword dynamic by itself, but Dynamic expression is what mess up ENTIRE project, just because one idiot decide to abuse dynamic expression so bad that we had to fire him. And this doesn't end there, Microsoft had to do another stupid move by spamming dynamic expressions on Excel Plugins. Most of the methods are made for single type input or output, putting a keyword dynamic over the hard type make this harder than needed.
    </rant>