Inside C# 4.0: dynamic typing, optional parameters, covariance and contravariance

Play Inside C# 4.0: dynamic typing, optional parameters, covariance and contravariance

The Discussion

  • User profile image
    How is the dynamic type different from the Object type?

    edit: nevermind, I never knew that C# couldn't do this.  VB has been able to do this since the beginning.
  • User profile image
    awesome cool...
    Thanx Charles...

    Just Downloading ..can't wait..

    Initially on listening about dynamic features i was not sure whether its good to include them..

    But after all the announcements & pdc talks.., i m really loving C# v4 , now we don't hav to write all the plumming code..that actually is pain..

    Ch9 ROCKS
  • User profile image
    Fact Pandit
    I am not sure whether "dyanamic" key word is a good feature or not. I think, if MS wants to provide run time object type resolution support in C#, it should have provided with a library or some thing. I don't like C# becoming another C++.

    I like the new covariance feature

    I like the named parameters, but I don't like changing the order. Also I don't like optional parameters feature. That creates an illusion and makes programmers to worry on non business aspects.

    My suggestion for optional parametes is:

    In the method declaration Use attributes to configure default values and while the programmer making invokation of that method let intellisence kicks in for filling the defaul parameteres.

  • User profile image
    Stop adding (polutting) new key word and syntax to C#.   It is a complex programming language as of now.  The more C# bloating with new stuff in each release (2.0, 3.0, 3.5, and now 4.0), the more it becomes a weaker programming language.    Comparing the number of keywords and programming constructs of C# to C/C++, Python, etc. and you will see how bloated C# has become.

    How about try to provide new features without modifying language for a change. 

  • User profile image
    Optional parameters can be a good thing when considering their example.  I remember automating some work in excel from c#.  I'm stealing this example from here :
    oChart.ChartWizard( oResizeRange, Excel.XlChartType.xl3DColumn, Missing.Value,
    Excel.XlRowCol.xlColumns, Missing.Value, Missing.Value, Missing.Value,
    Missing.Value, Missing.Value, Missing.Value, Missing.Value );
    [[ becomes ]]
    Source : oResizeRange,
    Gallery : Excel.XlChartType.xl3DColumn,
    PlotBy : Excel.XlRowCol.xlColumns

    The new version could be a one-liner if i wanted it to be.  I find the second version much easier to read, and you get to be explicit about your parameters. Intellisense was a lifesaver, I agree, but I do see the benefit of the new feature compared to just letting intellisense take over.
  • User profile image
    Hmm, ok I know we had the new language at .net 1.0,  C# 1.0, and added generics in .net 2.0 C#2.0.  extended Generics and added lamdas and extension methods in .net 3.5 C# 3.0. 

    Enlighten me on Language additions in .net 3.0?? 

    Each addition to the langauge so far has added little complexity in the return on productivity.

    As a matter of fact the co contra varient stuff should have been there in 2.0.

    The no pia enhancements is just a no brainer given the fact that .net has to interact with Com code.  

    I will take any language enhancement that simplefies that impedance missmatch. Or for that matter interacting with win32. 

    I further Hope Pray, Jump Up and Down Screaming  Waving my arms  Please please PLEASE implement compiler features to take advantage of the Recursion optimizations offered and .net 4.0 CLR. 

  • User profile image

    I'm half way through, and I have a question.

    Say you have the following:

    dynamic x = ...

    x.M(1,2,3,4,5,6,7,8,9,"a string");

    Will the generated delegate check parameters one at a time? eg, like this:
    if (param1Type == typeof(int))
       if (param2Type == ...)
        if (param5Type == int)
        else if (param5Type == double)
       { ..}
    } else if (param1Type == DateTime) {}

    Or will it check each one repeatedly?

    Also, will there be any sort of profile-guided optimisation in that delegate? Say that it notices  x.M(DateTime) is called the most, will it reorder the tests?

  • User profile image
    Hi Pon,

    At the risk of distraction from my main point, let me tell you what we do right now, and then I'll address your concerns about performance. The way the C# runtime binder works is that once it's located a correct "behavior" for a particular call site, it feeds that behavior back to the DLR, which manages the delegate. The DLR sequences these rules given the order that it receives them from the binder, and they do not interleave. Which I think means that in your example, we "check each one repeatedly." Furthermore, at the level of the delegate generation, there is no profile-guided optimisation.

    But that doesn't address your deeper concern about performance. Let me assure you that we care very much about the performance of the code that we're going to gen and that you're going to use, and we plan to measure it, set goals, and make changes to achieve those goals, both in the C# runtime binder and in the DLR. So it may be the case that the behavior I just described will change before we release the final version, or it may be that it's irrelevant. Consider that the delegate is going to be jitted and that the jitter could, in some cases, perhaps, perform the first optimization that you mention without the DLR having to worry about it. Obviously, in that case we wouldn't worry about it.

    I can't say what particular changes, architectural or otherwise, will come about because of our performance investigations, but I can say that there will be some.

  • User profile image

    Looks like you guys want to have the cake and eat it too Smiley
    From what you guys say, C# is moving from a pure classical language to add features of prototypical languages like javascript.

    Will you guys also be using JSON style name/value pairs to create heirarchical data structures with the "dynamic" data type?  I am guessing you will allow the developers to also "augment" the "dynamic" data type in a similar fashion.  If you do, how are you going to provide for encapsulation (everything is public access)

    The covariance and contravariance stuff is cool.  When I saw the example, I was thinking "duh, but of course"

    I like the optional/default parameters and named parameters too.  I have been wanting that for atleast 4 years now Smiley

    Keep rocking

  • User profile image

    I'm wondering what influence the optional and named parameters will have on interfaces and inheritance in general. Will a method parameter have to have the same name in an implementation as in the interface? This would help for code quality and maintainability. If not, will the compiler keep track of how a parameter gets renamed in the inheritance hierarchy or do all signatures get treated individually? Can a non optional parameter be made optional in an inherited method? What about the other way round?

    One more question: when will C# get XML literals like Visual Basic? I've been waintig for this since Comega...


  • User profile image
    Isn't late binding evil?  Don't we want compile time errors and not want runtime errors?
    I guess, if you have to interact with something non-native, this is pretty cool.

    Never mind, I think i got it Smiley
  • User profile image
    i think the people who's critical of the dynamic keyword really should watch anders session on pdc.. (future of c#)

    first of all, compared to fuby for example c# has relativly few keywords (including keyword overloads) imo

    the dynamic keyword is not exactly hard to learn, its basically just a special type, and it enables so soooo much.

    i dont think one should regard the dynamic keyword as a feature for c# per se, but for interop with other things that arent c#. there will always be need to talk to com, talk to js (in silverlight in perticular) and increasingly, talk to things written in dynamic languages. Thats what the dynamic is for..
    no one is suggesting that all c# code should be re written to use the dynamic keyword.. its just an option to enable things that used to be really hard or even impossible

    as anders said in his talk, convergence is the key. 

    watch the talk.. its pretty awsome Smiley
    great work c# team : ) cant wait to get my hands on this stuff Smiley
  • User profile image
    by the way, the true awsomeness of the dynamic keyword and the dlr is imo that you can create your own resolve mechanism.. for example in anders sessions he creates a dictionary that, if its cast to a dynamic, gets the keys from method calls:
    dic.key = value

    pretty heavy stuff..

    its its all just opt., you dont have to use any of the dynamix stuff if you dont want to Smiley
  • User profile image

    Ive worked a good amount between C# and COM. Optional parameters are nice, but i've found ways to work without them. I think allowing reordering of parameters is only asking for trouble. Especially in the talk the first thing talked about with this feature is how developers can screw themselves. I think it weakens the language to let things blow up at runtime rather than compile time.

    Great that these things are possible but I don't plan on using them.

  • User profile image
    Tanveer Badar
    According to Sam Ng, around 16:00, DLR binds arguments according to their runtime type. However, function overload resolution is based on static types of argument in all languages known to me. My knowledge could be lacking in this case.
  • User profile image
    Perhaps I'm missing something here - and somebody can point this out to me.  In regards to default parameters and named parameters, is this done at the compile time or run time?  If I am calling a external class as such Foo(x:1,y:1), and they change there class from Foo(x, y) to Foo(z,y), would I still work because it still has the same type of footprint because it was done at compile time?  I think it would, from what I got out of it.  However, if I recompiled mine, I should get an error as x no longer exists, and I should change it to z.  Now how about default params?  If I call Bar(x:1) to a defined method of Bar(x, y=3), then I would make the call with a value of 3.  But if the method is changed to Bar(x, y=7), do I make the call now with a 7 or a 3 - is it based on compile time or runtime?  I would hope it is runtime, as you grab the current value based on the current metadata of the class - but I don't know.
  • User profile image

    ive got a question about the method caching in the dlr..
    what if the arguments of a method is of type dynamic? lets say ive got a ruby int and a ruby string and i pass that into a ruby method M, all from c# (by calling libraries written in ruby for instance)

    how would the dlr cacher handle that? both the arguments whould be dynamic but actually contain diffrent types..
    im pretty sure the dlr handles it but it would be fun to hear more about that Smiley

    awsome work as always charles Smiley

  • User profile image
    Tell you one thing, the dynamic keyword is going to reduce the amount of code required
    to use reflection and such. I'm all for it.
  • User profile image
    I like the covariance extensions. I think it is also useful that C# is extended to consume COM interfaces, and integrate with dynamic languages. 

    But, can't you expose the dynamic as a plain class, and the optional/named parameters as attributes, rather than extending C# language syntax? It is there mostly for interop scenarios, and this will discourage people from using unless they have good reasons. 

  • User profile image
    In the example for overload resolution this example was given:

    M( int x, int y);
    M( string x, sting y);

    Then it was explained how the resoulution worked. It was said that the very first thing to be checked is if all the names are in the method's parameters. I found it strange that it does not do a simple argument type check before matching names in the paramters list. If you know you are getting two integers in the call, you know that the overload must accept at least two integers.
    So if you have:

    M( int x = 0, int y = 22, int z = 10, string text = "no");
    M( string x = "20", sting y = "90", int data = 200 );

    Suppose I  call M( y = 300, x = 200); The complier knows that I am giving the M two ints. If I now was to "check if all the names are there", that would yield both Ms. On the other hand by simply counting the number of parameters of each type in the call and comparing the counts with the overloads you will find the right one. There is only one M that accepts two ints or more. This will enables you to discard all overloads that does not have any chance at matching the signature, and focus on the ones that does in the later steps that involves name matching etc.

    I may just be plain wrong, and this may be inefficent for reasons I don't know. Maybe this even happens behind the scenes and just wasn't metioned in the interview. Just my thoughts after watching Smiley

    Great stuff btw Smiley
  • User profile image
    How is the dynamic type different from the Object type?

    if declare let#s say a COM-object as dynamic you can call it's methods, e.g.

    dynamic ApplicationClass = new ApplicationClass();

    if you'd declare it as object "wordApp.Quit();" wouldn't compile
    since it not a method belonging to System.Object

    Also all the stuff concerning the cacheing and analyzing done by DLR
    to dynamic vars, is a probably a huge differnce in terms of performance

  • User profile image
    I like the faeatures regarding co- and contravariance. I also like optional parameters.  But do we really need this dynamic stuff? Are there situations you need it (when you understand polymorphism?). Will there be a way to turn this feature off?

  • User profile image

    C# 4.0 is great and all, but HOW DO I GET ONE OF THOSE T-SHIRTS!!!

  • User profile image

    Regarding the complexity of overload resolution, it doesn't seem quite as bad as made out in the show (espcially compared to writing the compiler in the first place)

    Please note I am assuming you can't mix named and non named args in the same call - that would certainly complicate things.


    I agree the first thing is to consider the parameter names available to filter out invalid candidates.

    Second I would use the types to filter candidates further (considering valid implicit casts and base classes) This didn't seem to be mentioned.

    Then I would represent the candidate methods with a integer (with lots of bits) using 1 bit per arg.  Turn on these bits for each arg that is matched (by name) in the call. Turn on other bits that do not have an arg supplied in the call if they have a default value.

    Compare those integers with a mask representing the number of args in the candidates. Those that have all their args fulfilled remain candidates.

    If there is still more than one candiate overload, either throw an error, or have a policy to select the method.


    I'd be interested to get comments on this approach.

    Apologies if I've opened a can of worms. I've only given this 5 mins thought, but I have also written a complier.




  • User profile image

    I agree. I can't imagine what C# 10 will be like.

  • User profile image

    I agree in part.  The neat thing about python is that it is compartmentalized.  If you don't need functionality, you don't include it.  A language should be extremely simple and elegant.  If you need to build a skyscaper, you need a crane.  But you build the crane using smaller tools.  And you build those tools with basic simple tools. C# has become a do everything Swiss Army knife.  I am not saying that C# has become bloatware, but I will say that it is becoming dangerously close to being complex.  I have to wonder if that complexity is really necessary, and if it is, whether it is the result of a basic design defect that poses challenges that require the complexity to overcome. 



  • User profile image
    black orca

    no its gets wonderful and powerfull an programming technology


    go on Microsoft add most beatiful things too we are waiting;)Wink

  • User profile image

    My favorite part about all the new features is that, if you don't like, don't understand, or are frightened by them, you don't have to use them.  All your unpolluted old code still works.  For my part, I'm really excited to start incorporating a lot of the dynamic tools some of my compatriots have been enjoying for the last few years.

  • User profile image

    Another interesting article on .NET 4.0 dynamics can be seen here (  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.


    Feel free to re-link and follow!


    -Night Owl Coders

  • User profile image

    You guys are brilliant!

  • User profile image

    "My favorite part about all the new features is that, if you don't like, don't understand, or are frightened by them, you don't have to use them"
    Have you ever worked as a programmer? Maybe YOU don't use them, but then the guy down the hall does, and uses them badly because he doesn't understand them, and next thing you know you're fixing his awful code. At least, that's the source of this fear.
    Personally I don't worry much about most of these features, but covariance/contravariance worry me because they remove checks on type safety. I expect my C# code to be type correct as long as I avoid explicit downcasting (and now, the dynamic keyword), but this change to the language violates that expectation because it effectively allows implicit downcasting. And, worse, it allows it using the exact same syntax that I previously expected to be safe.

  • User profile image


Add Your 2 Cents