Future Focus I: Dynamic Lookup


by Charlie Calvert and Mads Torgersen

What is Future Focus?

This is the first of a series of monthly posts designed to give insight into the C# team’s current plans for future versions of Visual Studio. Each post will highlight one or more key subjects that will impact users of the C# language.  

It is important that readers of this column have the right expectations. The information in this column is meant to be a helpful guideline for C# developers, and not a binding commitment. We are not attempting to give a complete list of features in the product, but only to share what we can in a way that will be easily accessible to all C# developers. The Visual Studio schedule, unforeseen technical problems, intellectual property rights and competitive pressures may impact our schedule or our ability to share our plans. We will, however, do our best to keep you up to date on the latest news from the team as they design and implement future versions of the C# language.

Future focus is not designed to present a detailed specification of future features. Instead, its purpose is to outline in broad strokes, and easy to understand terms, the directions that team will take in the future.

Dynamic Lookup

The next version of Visual Studio will provide a common infrastructure that will enable all .NET languages, including C#, to optionally resolve names in a program at runtime instead of compile time. We call this technology dynamic lookup.

Work on support for dynamic lookup was begun in the CLR, but soon became part of the Dynamic Language Runtime, or DLR. The DLR provides the infrastructure on which a common set of dynamic tools can be built. For instance, the DLR provides the infrastructure for both IronRuby and IronPython. It will be the infrastructure on which the C# team implements dynamic lookup .

Support for dynamic lookup is already available in Visual Basic for .NET, where it is often known as “late binding”. The new release of .NET will provide C# developers with similar functionality, while at the same time providing a shared infrastructure for runtime name resolution across all .NET languages, including VB.

Useful Scenarios

There are three primary scenarios that will be enabled by the new support for dynamic lookup:

  1. Office automation and other COM Interop scenarios
  2. Consuming types written in dynamic languages
  3. Enhanced support for reflection

Office Automation

In the next version of Visual Studio Office automation will be easier. Developers will be freed both from the need for using a bulky type library, and the need for including optional arguments in their method calls. The support for Office Automation will be part of a general effort to enhance support for COM Interop and Office PIA.

Consuming Dynamic Languages

Dynamic languages such as IronPython or IronRuby are becoming increasingly popular. At this time, those languages can call C# code, but we can’t easily call into their code. The next version of Visual Studio will simplify the steps C# developers take to call into IronPython or IronRuby classes. This will give developers access to a useful existing code base, and an alternative way to write new code.

Call Reflection

C# developers can currently use reflection to instantiate classes and call arbitrary methods that are not known at compile time. The dynamic extensions to the C# language will make it much easier to make such calls.

Syntax

The syntax that will be used for dynamic lookup has not yet been finalized. The code that I show here is therefore only a tentative sketch that reflect the team’s evolving plans.

The team is currently considering adding the keyword dynamic to the language and using it to demarcate a block of code:

static void Main(string[] args)
{
    dynamic
    {
        object myDynamicObject = GetDynamicObject();
        myDynamicObject.SomeMethod();         // call a method   
        myDynamicObject.someString = "value"; // Set a field
        myDynamicObject[0] = 25;              // Access an indexer
    }
}

All the code that occurs in a dynamic block will potentially support dynamic lookup; even if the accessed members are not known by the C# compiler to exist, it will allow the code. At runtime the DLR will look at the actual object referenced by myDynamciObject for members with those names. It will access them if they do indeed exist, otherwise an exception is thrown. Outside of a dynamic block developers can only call C# code statically, just as they do today.

The details of the compile time process have not yet been determined. For instance, the compiler might treat all methods in a dynamic block as dynamic and only attempt to resolve them at runtime. Alternatively, it might first try to resolve them statically, and if that fails it will attempt to resolve them dynamically at runtime. As we gain more clarity on our design of this technology we will publish many more details.

Summary

In this edition of Future Focus you have learned about the team’s current plans for enabling dynamic lookup in the next version of the C# language. You have seen one tentative plan for enabling this syntax. You have also seen that dynamic lookup will be enabled for three code scenarios:

  • Office Automation in particular and COM Interop in general
  • Consuming types written in Dynamic languages
  • Enhanced support for Reflection

Mads Torgersen is a Senor Program Manager on the C# team. He has been working closely with Anders Hejlsberg and other key members of the C# team as they develop the plans for the next version of the C# language. Charlie Calvert is the C# Community PM.

 

kick it on DotNetKicks.com

Comments (201)

  1. You’ve been kicked (a good thing) – Trackback from DotNetKicks.com

  2. Jimmy Bogard says:

    What’s the usability scope of the "dynamic" keyword?  If it’s only inside method/property members, that will be quite limiting on its use.

  3. Interesting concept.  I imagine the runtime will do all sorts of nice optimizations to make sure that this runs nicely.

    However, given what you have now, what’s to stop you from implementing this as a compiler trick?  What is integration with the CLR going to give you over having reflected calls emitted by the compiler?

  4. ccalvert says:

    casperOne,

    The biggest thing that this gives you over reflection is ease of use. This is a much simpler syntax than we had through reflection as we know it today.

    Also, there is new functionality here in terms of COM interop and interaction with dynamic languages. Today those features are either missing altogether, or are very hard or awkward to use.

    I think it is a little early to start talking about performance. We are really giving you an early look at this technology, and it will be some time before we see it in more depth. Certainly I hope the performance will be great, but it is too soon to start making any claims.

  5. ccalvert says:

    Jimmy,

    The scope in the current plans would be to have it work only inside a method or property implementation, as shown in the article above. But our plans are still under development.

    Tell me what you are thinking about. Would you like to see it have class scope? Would you extend the scope across an entire namespace?

    It would be very wrong of me to give the impression that this is your chance to design a feature. That is not the case. But this is a chance for you to give us feedback. What would you like to see?

    – Charlie

  6. The intention is indeed for this to be efficient. A big part of the DLR’s job is to provide efficient execution infrastructure for code that is looked up at runtime – such as that of dynamic languages – Python, Ruby etc.

    /Mads

  7. Hi all, it’s me again. For those who don’t know me, I’m a tester on the C# IDE team at Microsoft. I already

  8. Jimmy Bogard says:

    @Charlie

    Our typical use for late-binding was Interop/Office scenarios.  We would create a single class to act as a facade over these COM resources.

    Sometimes COM classes can be expensive to instantiate.  In these cases, we would instantiate them at the constructor and set a private field.

    Also, COM references would frequently cross method (but not class) boundaries as we would do normal internal refactoring.

    For anything but dead simple scenarios, it would be difficult to accomplish what we need in one method.  As large as the Office interfaces are, there’s not a whole lot you can accomplish inside a single block before it gets complex and unmaintainable.

    In these cases, I wouldn’t necessarily need namespace-scoping, but file or class scoping would be sufficient.

  9. Hi all, it's me again. For those who don't know me, I'm a tester on the C# IDE team at Microsoft

  10. Bashmohandes says:

    I have been searching for any clue about the next version of C# and what the features to be included,…

  11. Klaus RM says:

    Great news that you are considering changing the access to Office Automation. I hate the optional parameters and the "missing, missing, missing" throughout the C# code.

    🙂

    Klaus

  12. Thomas Krause says:

    First of all, I think it is a great idea to give us an early insight in your future plans and let us give early feedback.

    My suggestion is to limit the scope of the dynamic-block to a particular variable or property and also to allow it in the declaration of (local) variables or maybe even properties and fields. This is, because in most cases you don’t want every lookup in your dynamic block to be dynamic, but only to some variables that e.g. contain COM-objects.

    So in the example above, I would rather see:

    object myDynamicObject = GetDynamicObject()

    dynamic(myDynamicObject)

       {

           …

       }

    or:

    dynamic object myDynamicObject = GetDynamicObject();

    Of course something like myDynamicObject.Foo.Bar would also work, but something like:

    object foo = myDynamicObject.Foo;

    foo.bar

    would not work and would require another dynamic modifier on the foo declaration.

    If you allow the dynamic flag on property or public field declarations, you could do it with some sort of attribute, but I’m not sure if this is a good idea, because developers using these properties or fields may not be aware of the fact that they are opting in for dynamic lookup. Also this may encourage bad programming style, where someone exposes lots of "object"-properties and relying on the dynamic lookup, where he could use other mechanisms to give the caller a statically typed way to access these properties.

    A compromise would be to allow this flag only in private property or field declarations, which would make a class scoped dynamic keyword (as suggested above) unnecessary and still allow for static typing for everything not marked dynamic in the class.

    I would love to hear your feedback on this.

  13. What kind of control do I have over it?

    That is, do we have a method missing hook?

  14. GauravKalra says:

    Finally, some news for next version coming up…

    Interesting …, i ll give my feedback …

    at first sight it seems to provide easy way for reflection…but there can be some interesting talks to it, like scoping or performance related..

  15. would be awesome of this worked on anonymous types

  16. Charlie Calvert has posted an article that is co-authored by Mads Torgerson on one possible implementation

  17. Tali says:

    What about the return types of the members you call dynamically. If we write something like:

    string x = (string)myDynamicObject.SomeStringMethod();

    would the runtime call SomeStringMethod and then try and cast the result to a string or check that the result can be cast to a string when it dynamically binds and throw an exception at bind time if it found that it was not possible?

    Would the runtime attempt to bind the entire dymanic block before it executes it (better since this would be more defencive) or dive in and try its best to perform the calls (and possibly cause an exception after only some of the calls had run)?

  18. Mark Dykun says:

    Adding to the Scoping of the Dynamic Object. We too use the object at the class level. For example we write an export class that has a single handle into Excel. Having the scoping at the method level will severly limit the cross method calls. Unless we can declare the object as DynamicObject in the calling method.

    private void CreateHeaders(dynamic object excelObject, string[] headers) {

    dynamic(excelObject) {

    }

    }

  19. ccalvert says:

    Jimmy and others who addressed the scoping issue:

    Taking into account the fact that our plans are still fluid, and nothing is finalized yet, the current thinking is that there will be no reason to consider a dynamic variable as anything special, and so it can be declared as we would in standard C# 3.0 code. For instance:

    class MyClass

    {

      object myDynamicOfficeObject;

      public void Method01()

      {

           dynamic

           {

                myDynamicOfficeObject = GetMyDynamicOfficeObject();

                myDynamicOfficeObject.Format();

           }

      }

       public void Method02()

       {

           dynamic

           {

               myDynamicOfficeObject.SelectRange();

           }

      }

    }

    If one calls Method01() first, then myDynamicObject will still be fully initialized and in scope when one calls Method02().

    The idea of declaring an entire object as dynamic is also in play, but there is a concern that a broad granularity of that type is not right for C#. So currently we are leaning toward the syntax shown above.

    But all of your suggestions are being taken into consideration and we appreciate your feedback. It is valuable.

    – Charlie

  20. Olmo says:

    Mmmm that sounds so VB… does it mean that the F# tunics have left the team and hand been replaced again by the VB Ties?  

  21. Tom Kirby-Green says:

    It’s interesting because there’s a C9 video where Anders goes on record saying that he’d think twice before putting this kind of feature into C# rather than leaving it to VB.NET. I guess market pressures are such that MS need to ensure they have something that ticks the Dynamic Box. Given that the CLR is meant to be all about using the best language for the job I don’t quite see why MS don’t put more effort into promoting *mixed* language solutions – rather than trying to shoehorn every language idiom and school into C#…

  22. Thomas Krause says:

    What I don’t understand:

    If everything inside the "dynamic"-block uses  dynamic lookup, then you’ll loose type safety for everything inside this block, not just the objects you’re really needing it for. This is a much broader granularity IME than declaring a single object as dynamic and leaving all the other objects typesafe.

    In a typical scenario you’ll need every access to a specific object to be dynamic. If you just declare this single object dynamic, you’ll have fewer dynamic lookups than having many dynamic blocks in a class that contain dozens of other objects that would normally be just fine with static lookup, but now use dynamic lookup, just because a single object in this block needs it.

  23. ccalvert says:

    Thomas,

    Thank you for this helpful comment. As you know, this is one of the subjects that is still very much under discussion. For instance, the team is considering first attempting to resolve all code in a dynamic block statically, and using dynamic lookup only if the static calls can’t be resolved at compile time. The team will take your feedback into account and I’ll work to get updates to the community if and when the status on these issues changes.

    – Charlie

  24. ccalvert says:

    Thomas,

    Thank you for this helpful comment. As you know, this is one of the subjects that is still very much under discussion. For instance, the team is considering first attempting to resolve all code in a dynamic block statically, and using dynamic lookup only if the static calls can’t be resolved at compile time. The team will take your feedback into account and I’ll work to get updates to the community if and when the status on these issues changes.

    – Charlie

  25. Welcome to the fortieth issue of Community Convergence. This week we have two new releases of note: We

  26. Welcome to the fortieth issue of Community Convergence. This week we have two new releases of note: We

  27. Steve says:

    I agree with Thomas.  I think that the typical scenario has us using dynamic lookup for all references of a single object, so it makes sense to declare the object as dynamic rather than a block of code.  Something like this:

    class SomeClass

    {

       dynamic object _myLateBoundMemberObject;

       object _myStaticallyBoundMemberObject;

       private void SomeMethod()

       {

           dynamic object myLateBoundLocalObject;

           object myStaticallyBoundLocalObject;

       }

    }

    ~Steve

  28. commenter says:

    How about using -> instead of . for dynamic lookup? I’m only half joking!

  29. David says:

    I agree with Tom (and Anders, apparently). It is silly to try to make C# everyman’s language. Why can’t the C# language team admit that it’s ok to have statically typed languages for some purposes and dynamically typed languages for other purposes? You don’t have to take EVERY SINGLE programming convention or idea or trick and find a way to squeeze it into C# somewhere. Personally, I WANT C# to stay away from dynamic language features; I use it because I want a statically typed language. When I want a dynamically typed language, I can reach for one of the many available. You don’t have to try to be everything to everyone.

    That said, if you are hell-bent on doing this regardless of its advisability, then I also agree with Thomas. If you take a step back from the technology and look at the typical use cases, usually the only times you need to use dynamic invocation is because you have created an object for which you do not have static access to its members, i.e. it was constructed from a dynamic language library, or through reflection. Therefore, it would make a lot more sense for the dynamic keyword to be used at the variable declaration level, allowing all calls on that variable to be dynamic without having to clutter up all of the code that might use that variable with dynamic blocks.

  30. Pablo says:

    If I understand what your doing, this is really just another C# compiler trick where your just going to replace it in IL with a reflection version.

    If got that right, then I also prefer a new Dynamic Lookup method operator instead.

    ‘->’ might cause many C++ refuges some heartburn, so how about:

    myLateBoundLocalObject’Method1()

    or

    myLateBoundLocalObject~Method1()

    or

    myLateBoundLocalObject@Method1()

    or

    myLateBoundLocalObject..Method2()

    or even reverse it to make them stand out more

    aka

    Method1() of myLateBoundLocalObject

    or

    Method1()@myLateBoundLocalObject

    I think if a good operator is found it would make the code much cleaner.

    I personnally like the ‘..’ version as it would be easy to remember.

    One period for Static bound calls,

    Two periods for Dynamic lookup.

    -Pablo

  31. Paul says:

    Quick suggestion: could the "dynamic" modifier be implemented as an attribute?  That way the attribute could be applied to a variable, class, function, etc.  That would address the scope issues presented earlier, and it would be easier to read and comprehend the code.

  32. Dejan Stanic says:

    Kinda OT, but since somebody important could be reading this…

    Can we /please/ have something like ‘:’ operator, so that following could be written:

    string greatGrandFatherName = person:Parent:Parent:Parent:Name;

    …instead of tedious…

    if (person.Parent == null) return null;

    if (person.Parent.Parent == null) return null;

    if (person.Parent.Parent.Parent == null) return null;

    return person.Parent.Parent.Parent.Name;

    OK, this isn’t the best example, but there are many uses for this (especially in ORM) and it makes syntax so much cleaner, IMHO.

    LP,

    Dejan

  33. Octavio Hernandez says:

    This reminds me of the times when Delphi first added late binding features in order to support COM automation scenarios…

  34. I often rethink or have additions to my posts. This topic of what’s coming in C# vNext is definitely

  35. Hans Olav Stjernholm says:

    Hi. Thanks for a great post Charlie and Mads!

    I’ll post some of my feedbacks here.

    What about a dynamic block and a new late bound operator (.. for example):

    object myObject = GetDynamicObject();

    dynamic

    {

     int i = myObject..GetValue();

     string s = myObject.ToString();

    }

    This way you spesifically choose to do late binding and show exactly here you want it. But this kind of breaks the nice typesafe static nature of C# I guess…

  36. Hans Olav Stjernholm says:

    This is so fun I have to put out another idea…

    What about some kind of inline interface declaration?

    object myObject = GetDynamicObject();

    dynamic

    {

     interface (myObject)

     {

       void SomeMethod();

       int GetSquare(int v);

     }

     catch

     {

     }

     myObject.SomeMethod();

     int i = myObject.GetSquare(100);

    }

    This way you both declare a dynamic section and declare the exact members you need.

    There’s actually no real late binding, just a syntactic sugar for reflection lookups.

    Another nice feature here I think is the possibility to catch if the lookup fails.

    You could even start a new interface failover declaration inside the catch.

  37. ccalvert says:

    David,

    Thank you for your comments. The team will consider them carefully. Please note that the proposed C# features discussed in this post are not designed to convert C# into a dyanmic language, only to make it possible to call code written in a dynamic language and to make COM interop simpler.

    I and others on the team hear and appreciate what you are saying in your second paragraph about the declaration of dynamic variables and I will pass that information on to everyone on the team.

    – Charlie

  38. commenter says:

    After posting the -> ‘suggestion’ I decided that ‘..’ would be a reasonable looking alternative. So there you have it – independent evolution of the same syntax idea from multiple people – it must be a good idea 🙂

    The whole thing reminds me a bit of the old VB syntax for accessing fields on a recordset:

    Sn!FieldName ‘instead of Sn.Fields("FieldName")

  39. I vote strongly in favour of Thomas Krause’s suggestion.

    I think a tagged block (similar to "unsafe") that changes the language rules for all code inside it would be a bad idea.

    Firstly, if you made it affect all types within the block, that’s too coarse-grained – what if some calls could be static? This immediately leads to the idea of mixing dynamic and static lookup, as mentioned.

    Secondly, the main reason for using that tagged block approach is because you want to clearly call it to the attention of someone reading the code, but in fact if all the code in the block happens to be statically resolvable then the dynamic block would not make any difference, and so would be completely misleading to anyone reading the code. It’s like a worrying comment that might have genuine implications, but might not.

    Far better to have a pseudo keyword made of two tokens, "dynamic object", which declares a reference type on which method/property access is always dynamic. This can then be used on local variable or member declarations.

    As for making it clear to the reader of the code, Visual Studio can do a much better job of this by highlighting all method/property accesses on dynamic objects. It would be great if they had a grey background or something like that – they’d stand out a mile and it would give instant feedback to explain why there was no intellisense happening.

  40. ccalvert says:

    Thomas, Daniel, Commenter, others,

    Thanks for these suggestions. This is great feedback and it is very much the type of thing we were hoping to see. I’ll make sure all your ideas are passed on.

    – Charlie

  41. I have to agree with Thomas on this one

    dynamic object myDynamicObject = GetDynamicObject();

    I think that c# should remain explicit when it comes to this new feature of dynamic objects. I much rather declare an object as dynamic.

    Imagine a scenario where I have a private member variable that is dynamic. If we state it as such on the declaration we will not have to litter our code with

    dynamic {

    }

    on each of the 10 functions that we require to use that object.

    This also has the added benefit that you can specify a return value of dynamic object on functions. You would then have the ability to know which functions return dynamic objects on that 3rd party API that I am consuming as a programmer.

    I think it is important for c# to remain a language that is explicit in telling the compiler how to do things. I would not like to see the compiler trying to get overly smart and trying to guess within a dynamic region what really *is* dynamic and what is *not*

    On a side note I think Dejan has brought up an important missing nicety in c#. I too would like to see a null dereferencing operator of some sort in the form of myobj.?property  or with a symbol of your choice

    Thanks,

    Anastasios

  42. Hans Olav Stjernholm says:

    Wouldn’t it be cool to support both late binding and intellisense.

    I think optionally declaring methods and properties in the variable declaration could do.

    public class Program

    {

    // Without intellisense

    dynamic object dynObject = GetDynamicObject();

    // With intellisense

    dynamic object dynObject = GetDynamicObject()

    {

    void SomeMethod();

    }

    }

    This way you can opt for intellisense according to own needs.

    And it could also be possible to declare inline:

    dynamic (dynObject)

    {

    int GetSquare(int value);

    }

    int i = dynObject.GetSquare(100);

  43. Hans Olav Stjernholm says:

    This is kind of off-topic, but since we’re talking about C# future I would like to suggest an implementation for optional parameters.

    I understand why C# doesn’t allow them since this transfers control from the user of a method to the implementor,

    and the implementor can choose to change default values at any time, possibly breaking the code using it.

    But what about declaring default values and letting intellisense auto-insert them for you?

    Here’s a code example:

    public void PlaceOrder(int orderID, int price = 100);

    Then, when you write PlaceOrder intellisense will autofill the price param to be 100 if you want it to.

    This doesn’t make a lot of sense when there’s one parameter defining a default value,

    but with 10 it could really boost productivity.

  44. Chris says:

    I hope this just uses reflection under the hood and doesn’t alter the .NET framework to accomodate late binding in anyway. Much like var in C# is just a compiler trick

  45. zproxy says:

    Maybe this syntax instead:

    var myDynamicObject = p as dynamic;

    myDynamicObject.SomeMethod();         // call a method  

    myDynamicObject.someString = "value"; // Set a field

    myDynamicObject[0] = 25;              // Access an indexer

  46. wkhazzard says:

    I do this today by using a PythonEngine instance in my C# applications. It’s clunky but it works. The PythonEngine instance acts as the scope for the dynamic code. I can inject scripts into the engine using Execute() and fetch objects from the engine with Evaluate(). I use this sort of "dynamic layer" at the lower edge of my client applications to dynamically generate ClientBase<T> derived instances from WS-MetadataExchange using classes from the System.ServiceModel.Description and System.CodeDom namespaces. Imagine a SVCUTIL-free lifestyle. No proxy generation at all. It’s nirvana, really.

    I like Thomas Krause’s proposed model where the objects to be used within a dynamic scope could be obtained outside of that scope because it would make what I’m doing with Python embedded in C# much simpler. Of course, I probably wouldn’t be using Python to glue the WCF clients and services together with C# 4.0 if it supported what Charlie’s talking about. But it would need to be done as Thomas describes to make it really fluid. Thomas’ reply on 28 Jan at 13:29 seems to indicate that the C# team might be leaning this way. And that’s good because the main problem I have today is making the dynamic Python code reach out of the dynamic scope to access object references obtained in the static scope. It’s possible but really messy.

    While I’m in here and on the topic of language futures, how about a policy attribute that I can attach to a class that forces it to be instantiated within a using statement? In other words, for a class that implements IDisposable, give me an attribute that I can mark the class with so that any attempt to instantiate the class in a way that would not invoke IDisposable::Dispose would simply not compile. Man, would that be helpful?!

    – Kevin

  47. Kudos to Brian for editing everything last night, I think he’s sleeping on my couch right now, but our

  48. Kudos to Brian for editing everything last night, I think he&#39;s sleeping on my couch right now, but

  49. This is Episode #1 of &lt;insert.name.here&gt;, a weekly recap show of our favorite things for developers

  50. Eric Newton says:

    Personally, I have to side with the guys that like C# to stay static.  LINQ is about the extent of "dynamic-ness" that I can tolerate.  

    Class Libraries written in IronPython callable by C#?  I honestly can’t see many truly indispensible class libraries written in IronPython that couldn’t otherwise be rewritten in a much more performant way in C#.  

    Granted, usability is key here, but are we in the community asking for this?  My assertion is "USE VB" since VB frankly is so close to C#, yet still has the late binding techniques built in.

  51. commenter says:

    Eric, there’s a language for people like you (the instinctively conservative).

    It’s called Java. 😉

  52. wkhazzard says:

    Eric, I understand your thinking about keeping C# statically typed. I sometimes wonder if the current duck typing pendulum has just swung to the far end of its period as it’s known to do every few years. But I don’t think so. This time, I think there is enough maturity in the marketplace that people are beginning to wonder why they can’t have the best of both worlds.

    My response above about my experiences embedding Python in C# is an expression of the fact that I love the type safety of C# most of the time. But when it’s time to do something dynamic, I regret having to step out of C# (or into deep reflection and lots of CodeDom trickery) to do it.

    Speaking of performance: for the dynamically-generated ClientBase<T> invocation of a WCF service in a tight loop versus using a statically-bound, SvcUtil-generated proxy called directly from C# that I described above, there is no difference in performance. The only real difference is that I never had to use SvcUtil in the former case and I really like that. So I can envision a world where static, early-binding and dynamic, late-binding get along just fine.

  53. C# Futures – Dynamic Code Blocks

  54. This is an exciting feature.  I have several comments.

    1. I really like the .. operator idea either instead of or in addition to a dynamic block.  This is even more important in a maintainence scenerio than in new code.  If one is adding 2 dynamic calls to some existing code the choices are a) 2 dynamic blocks or b) subtly changing the semantic of all the method calls between them.  I really want more control over when I use dynamic invocation.

    2. I hope you will expose the the name lookup logic through system.Reflection as well.  I have been trying to write a generic "accessor" class that uses reflection to allow unit tests to access private and protected members of production classes.  Doing the name resolution, based on a string member name, is easy to do wrong, and proving very difficult to do right.  I would enjoy being able to give reflection a name and say "find me the member, public / private  … etc, that this name would map to."

    3. WHat is going to happen when you do a Dynamic call on a RealProxy descendent.  I hope that it just calls Invoke with the method name and arguements, and lets me work it out.  (This would let me define some test objects with a very flexible interface.)

    4. Add another vote for the : operator proposed by Dejan Stanic.  I see this pattern all the time, especially when using Linq.

    John Melville

  55. Jon Galloway says:

    I’ve had a policy against posting on big news that’s likely to be common knowledge in the Microsoft development

  56. This is the kind of feature that should be introduced with extreme care, since a) it’s too easy to implement (so the temptation to include it will be high, even if consequences have not been considered thoroughly) and b) if badly done, it can spoil forever our beloved language.

    Strongly agree with others that a dynamic {} block is not the best solution, whether dynamic in that context means "every member access will be dynamically looked up" (too coarse-grained) or "access to members not found at compile time" (also coarse-grained and may complicate understanding of the code).

    Explicitly supporting "dynamic" in front of "object" in declarations (as Daniel proposes) seems much better to me. For instance, in the example of wkhazzard one could define a method:

    public class ProxyGen

    {

     dynamic object GetProxy() { /*…*/ }

    }

    and then the client would use:

     ProxyGen p = new ProxyGen();

     dynamic object cli = p.GetProxy();

     cli..Whatever();

    I also support having a special operator (I’d prefer ->, but it’s already used in unsafe blocks), so that these dynamic method calls are explicitly marked in code.

    Best regards,

    Octavio

  57. Miguel de Icaza says:

    The idea of adding late binding to C# is a good one, but am not sure that going down the path of using a block marked by the dynamic keyword is a good idea.

    The rationale seems to be that "dynamic" would clearly flag a block of code that will have special rules, but the problem as I see it, is that there will be no way for the programmer to go back and forth inside this block to get strong typing (without doing plenty of gymnastics).

    By using the ‘dynamic’ block, everything inside this block that happens to be an object will be treated as a dynamic path and some errors that could have been caught will not be (accidental uses of it, return values that should really have been strongly typed).

    My preference would be to additionally declare variables with a keyword, an attribute or a new type, like this:

    dynamic p = GetDynamic ();

    p.Hello (d.World.DoSomething ());

    This has the advantage that dynamic support will only be offered for "p" in this particular context, but still get full type checking with d, d.World and d.World.Something.

    Miguel.

  58. Andrew Davey says:

    Give us an interface we can implement on our own classes that allows us to implement method dispatch! The Boo lanaguage has IQuackFu – silly name but very powerful.

    Something like this would be cool for C#:

    class MyFoo : IDynamicDispatcher

    {

      object IDynamicDispatcher.Invoke(string methodName, object[] args)

      {

         // …

      }

      // similar for properties here…

    }

    then use as:

    dynamic foo = new MyFoo()

    foo.Bar()

    Compiler translates into:

    foo.Invoke("Bar", null);

  59. wkhazzard says:

    Miguel, what about scoping? Consider this:

    ShoppingCart cart = new ShoppingCart();

    dynamic jabberwocky = GetDynamicObject();

    Product P = jabberwocky.SomeUnknownMethod( cart );

    To do this today, I have a couple of options:

    (1) I can use reflection and find the SomeUnknownMethod signature for jabberwocky that best accepts a ShoppingCart, then call it, coercing the result into a Product reference.

    (2) I can instantiate a ScriptScope from the DLR, inject the ShoppingCart object using SetVariable, invoke some Python, for example, to do the work, then use GetVariable<T> to fetch the Product out of the script context.

    Personally, using the DLR seems like a better, long-term, more flexible option but it us certainly heavier than using simple reflection.

    I suppose the question I have for Charlie and others on the C# team is: how will late-binding in C# make it easy to write code like that above. I need to move data easily in and out of the dynamic scope from the surrounding static scope, whether it’s a single object marked dynamic or a whole block. And it needs to be predictable with respect to the scoping rules in both forms. I can’t help but think about how statement lambda expressions and anonymous methods reach out into the surrounding scope as needed. The problem with dynamism though is know which references should reach out and which ones should not.

    I suppose the more I think about this, the more I wish that the DLR were injectable into the statically typed scope, making (2) that I described above a bit easier to write.

    One last thought: assuming that it comes down to marking an object as dynamic (not a block), what would be the harm in enhancing the var "type" to do this, allowing:

    ShoppingCart cart = new ShoppingCart();

    var jabberwocky = GetDynamicObject();

    Product P = jabberwocky.SomeUnknownMethod( cart );

    instead.

    — Kevin

  60. she says:

    First impression:

    WOW

    Second impression:

    I am not entirely sure… i still go "wow" but I have maybe a few concerns. The dynamic{} code might look a bit awkward. Also what about totally prototype like code, like where objects are not tied to a particular class, but instead can be shaped lateron? And aside from this, what happens when objects are modified or extended at runtime, can these changes be reflected back upon the C# world?

    Anyway dont get me wrong, so far it looks great

  61. Marvin Steakley says:

    Maybe I have an oversimplified view of this subject, but have you considered something like this?

    static void Main(string[] args)

    {

       interface IMyInterface

       {

         void SomeMethod();

         string someString { get; set; }

         int this[int index] { get; set; }

       }

       dynamic IMyInterface myDynamicObject = GetDynamicObject();

       if (myDynamicObject != null)

       {

           myDynamicObject.SomeMethod();         // call a method  

           myDynamicObject.someString = "value"; // Set a field

           myDynamicObject[0] = 25;              // Access an indexer

       }

    }

    where the dynamic keyword tells the compiler to emit code that at runtime compares the signature of the interface with the signature of the object. myDynamicObject would be set to an instance of the interface that is a proxy to the object if they are compatible otherwise it would be set to null.  All the user of the object would compile and run as it does today.

  62. Jim L says:

    For all the reasons Eric mentioned, and then some, please tread softly here. If you really need to do this, you can already do this. Make it too easy, and you’ll have every idiot who thinks code reuse is done with ctrl-c,ctrl-v making every single call dynamically. This is the problem we currently have where people use generics willy-nilly thinking they are writing code in a generic fashion, not realizing what the compiler does when it comes across generics.

    Speaking of generics, how do they match up with dynamic? Bit of an interesting topic, I’m sure.

    Also, performance, performance, performance. The word Dynamic translates into "trading performance for developer convenience" in just about every case you come across. A lot of developers don’t make the connection that doing things dynamically makes for extra load at run time most of the time.

  63. Charlie Calvert blogged about dynamic support in C# 4.0 . I love this for two reasons. One it will enable

  64. Charlie Calvert blogged about dynamic support in C# 4.0 . I love this for two reasons. One it will enable

  65. Ben says:

    Firstly, I apologize for my negative comment. I realize that things are early and that there are surely many other announcements in the near future.

    C#1 was a great start and C#2 was brilliant. Hands down the best thing about version 2 was the work done to support generics.

    However, I was extremely disappointed with C#3. Almost everything introduced was nothing more than syntactic sugar. It enabled nothing that I could not already do before.

    Now comes "dynamic lookup". Again, nothing that I can not already do with reflection.

    I’d like to see new features that enable new scenarios. Two in particular that I have been really missing are support for 1) generic variance and a way to do 2) generic operator overloading (can’t constrain T to a static method).

    With that said, I’m looking forward to hearing more about the future of C#. Hopefully the next version will be more to my liking.

  66. Craig M. says:

    I agree with David. I use C# because it is statically typed. That is also why I stay away from VB and languages like IronPython etc. I do *not* want dynamic code in my C# code.

    Carlie Calvert wrote:

    "Please note that the proposed C# features discussed in this post are not designed to convert C# into a dyanmic language, only to make it possible to call code written in a dynamic language and to make COM interop simpler."

    Understood. However, it should be put in a library, not built into the language. I think that reflection is sufficient, but now that we have the DLR, just extend it as needed.

  67. David Thompson says:

    Thank god!

    I have recently written screeds of reflection based code – there was no other way. I was crying out for something like this. To those who say "use python" or whatever… I don’t have the choice and guess most devs don’t either.

    Oh yeah, please give us something like Missing Method from smalltalk it adds a lot of power in dynamic dispatch use cases.

  68. Any chance of having a similar keyword in Visual Basic?  It’s neat that I can already make dynamic calls in VB, but I believe it currently requires one to turn Option Strict Off.  Something more fine grained would be awesome.

  69. Adrian H. says:

    C#小组CharlieCalvert在其博客发了一篇有关C#语言未来方向的文章,这片文章介绍了一个叫做动态查找的特性,它为.NET语言(包括建立在DLR上的语言)能有一个统一的动态运行时名称绑定方案…

  70. commenter says:

    Quote: "Now comes "dynamic lookup". Again, nothing that I can not already do with reflection"

    Might I suggest assembly language? There’s nothing you can’t do in it, and there’s none of that nasty ‘syntactic sugar’ you seem to object to. Seriously.

  71. Çağlar Gülçehre says:

    I think it will be very cool but probably unnecessary if the .Net frameworks let using multiple planguages in a class. A special project type class extensions may be defined or may be a syntax like below can be used:

    @Use Language=VB .Net

    … Some VB .Net Code

    @End

    But by the way this may reduce readability and could make the code look uglier or messier.

  72. ccalvert says:

    Tali,

    There would still be strong type checking on variables declared in a dynamic block. If a method declares that it is going to return a string, or a DataTime, then an exception would be raised if a compatible type were not returned.

    Right now, it seems likely that each call in a dynamic block will be handled individually, so that some of them might execute and then an exception would be raised if one failed. These plans are not certain, but that is the most likely scenario.

    – Charlie

  73. ccalvert says:

    Commenter,

    You asked:

    "How about using -> instead of . for dynamic lookup"

    This type of thing was discussed in depth. Early drafts of the team’s plans tended to include it, but now the team is leaning away from it. No decisions have been made at this point in time, of course. And there were various different characters proposed, not necessarily focusing on the C like syntax you suggest. But still in the same general vein.

    – Charlie

  74. John Rusk says:

    I also strongly agree with Thomas.  

    I’ll also throw one other option into the mix.  What about something like this

    object myDynamicObject = GetDynamicObject();

    myDyamicObject."SomeMethod"();

    The quotes around the method name make it clear that, as far as the compiler is concerned, the name of this method is just a string, to be looked up at runtime.

    To me, the main thing is to find something that doesn’t require a block to be wrapped around the code, and which lets me (any my IDE’s syntax highlighing) tell exactly which calls are dynamic – either by the variable they are made against (as in Thomas’s suggestion) or by the way the call is written.

  75. Jackob says:

    This belongs in a library, not baked into the language.

    We have reflection and we have DLR. You said that the DLR will be the "infrastructure on which the C# team implements dynamic lookup." If the existing DLR infrastructure is not sufficient, then why not just extend it? I fail to see what advantages special syntax will provide over a pure library implementation. It serves no purpose but to further pollute the language when a library is the appropriate place to be doing this.

    I am strongly opposed to this.

  76. Eric Nicholson says:

    Based on my experience with VB (which really already has this), I agree with Thomas & Miguel. Blocks are the wrong granularity.  Either variable or call level would be great.

  77. L’�quipe de C# d�voile un peu plus sur les principaux prochains ajout du langage avec l’aide de rubriques nomm�s Future Focus. La premi�re de la s�rie concerne le Dynamic Lookup….

  78. David says:

    @Charlie – "The idea of declaring an entire object as dynamic is also in play, but there is a concern that a broad granularity of that type is not right for C#."

    I couldn’t disagree more. Declaring an entire block to be dynamic is what is too broad. Declaring a single object is a more narrow approach that allows the developer to target the dynamic calls more appropriately. Perhaps even forcing individual calls to be made using a dynamic syntax would be the right way to go. But forcing a developer to use a dynamic block every time they want to make a dynamic call just makes the code harder to read.

    @Thomas – "If everything inside the ‘dynamic’-block uses  dynamic lookup, then you’ll loose type safety for everything inside this block…"

    @Charlie – "…the team is considering first attempting to resolve all code in a dynamic block statically, and using dynamic lookup only if the static calls can’t be resolved at compile time."

    You’re talking about early binding; Thomas is talking about type safety. They are two different things. Sure, you can still early bind to anything that is statically accessible; but for anything that is not, you turn it into a dynamic call. So the developer has no way of knowing that when he mistyped that method name, instead of getting a compiler error, it gets turned into a dynamic call instead, which results in a run-time error.

    The more I think about this whole thing, the more I think it is a bad idea that will lead to long-term negative consequences. Giving developers a way to easily lookup and execute dynamic calls at runtime is a good idea; baking into the syntax of the language is not. Can you please explain why you feel it is necessary to make it a part of the language, when you could just make it a part of the reflection library, or its own library, and it would function just as well, not to mention be useful in other languages as well?

  79. John Rusk says:

    David,

    * Type safety

    Good description.  Further to the points you’ve made, I think it might actually be helpful if "dynamic object" is the only kind of dynamic variable that can be declared. E.g. you can’t say "dynamic someOtherClass".  That  reduces the confusion that could arise from having a mix of early and late bound calls on the same variable, since so few early bound calls are actually possible on "object".

    * Why not use a library?:

    I presume that the desire to put it into the language is because that gives the cleanest and most compact syntax.  I would imagine that the cleanest that a library-based approach could look would be something like this:

    object myDynamicObject = GetDynamicObject();

    myDynamicObject.Dyn("SomeMethod")()

    In this hypothetical example Dyn(string) is an extension method, that does the reflection and returns a delegate to the named method, which we can then invoke.

    The problem is in passing parameters to the delegate, even though the compiler doesn’t know it’s type.  That might require a language change to introduce some kind of "dynamic delegate", which is a delegate that you can call with any parameter list you like, without the parameters being checked at compile time. E.g. allow this

    dynamic delegate d = …

    d("Foo", "Bar", 10, false);

    instead of this

    delegate d = …

    d.DynamicInvoke("Foo", "Bar", 10, false);

    There might be no need to actually use the "dynamic" keyword on the delegate.  Instead, it could be set up so that all calls on delegates typed as "delegate" are dynamic  – i.e. d(params…) equates to d.DynamicInvoke(params…) – but all calls on strongly-typed delegates (i.e. subclasses of "delegate") are early bound as they are now.

    While this involves less messing with the language, it still requires some change, it doesn’t really support setting properties dynamically, and the syntax is a bit more ugly than a fully language-based solution.

  80. Rob says:

    I’d much rather see something like this (as others have already stated)

    dynamic myDynamicObject = GetDynamicObject();

           myDynamicObject.SomeMethod();      

           myDynamicObject.someString = "value";

           myDynamicObject[0] = 25;

    or perhaps

    [dynamic] IMyInterface myDynamicObject = GetDynamicObject();

    The block idea is a bad idea in my opinion.  I’m sure it’s easier to implement, but is that good for the language in the long run?

  81. Rune FS says:

    The idea of the interface posted by Hans gave me another similiar idea.

    I like the fact that c# is 100% type safe and I like that i can rely on that.

    But even so I do see where th Dynamic typing could be nice to have.

    but instead of

    dynamic

    {

     object MyObject = GetDynamicObject

    }

    how about:

    internal dynamic class MyDynamicBasedClass : DynamicClassIdentifier

    {

    public dynamic void SomeMethodOnDynamicObject(string someargument);

    public void MyWonMethod(){

    //do nothing and return

    }

    }

    That would make the coding style the same as we have it today. It would be kinda type safe. It would meet the wishes of Thomas and others and it would be very readable and intellisense enabled (with a new icon for dynamic methods/properties o.c.)

  82. Vikas Burman says:

    Lots of ideas, issues, problems, solutions…

    Its actually good taking feedback from community – such brainstrorming would help in getting it right the first time – a must for a language feature like this.

    I too have my suggestion:

    /// start

    // define an interface normally as we do now

    interface theDynamicObjectInterface

    {

       void SomeMethod();

       int theProperty {get; set;}

    }

    // Something of this sort we do currently as:

    //

    // theDynamicObjectInterface theDynamicObject = (ItheDynamicObjectInterface)new theDynamicObjectClass();

    //

    // the above syntax gives a runtime error "Unable to cast…" if iterface and class implementation do not match

    //

    // this behavior can be altered by an explicit interntion of developer as:

    dynamic theDynamicObjectInterface theDynamicObject = GetDynamicObject();

    // this syntax will automatically try to cast returned object as the specified interface and

    // if there is an error, object will be set to null

    // here after there are normal calls which otherwise also we do

    if (theDynamicObject != null)

    {

      theDynamicObject.SomeMethod();

      theDynamicObject.theProperty = 10;

    }

    /// end

    I might me missing compiler internals here, but I guess the idea is communicated.

    Points to note here:

    1) One point resolution for member mapping, i.e. at the time of assigning object to specified interface

    2) Full intellisense

    3) No special delimiter required for call-to-call basis mapping (.. or ->, etc.)

    4) No dynamic code block

  83. adam s says:

    what I’d really like similar to this is an infered duck typing. That way I get type safeness and intelisense but don’t need adapters.

    In my example the 2 methods (f1 & f2) have return types which do not implement IHasText, however they both honour the interface. A new *infer* keyword could behave like the *as* keyword and return null if a type cannot be coerced into the supplied interface. Under the hood the compiler can follow the adapter pattern or what ever clever stuff is required 🙂

    e.g.

    IHasText{string Text {get;}}

    Label f1(){}

    TreeNode f2(){}

    void func()

    {

     var ht = f2() infer IHasText;

     // use ht.Text

    }

  84. Microsoft haven&#39;t committed to anything in C# 4 yet. However, there have been hints about what they&#39;ve

  85. Jay R. Wren says:

    C# 4 slicing index notation ala python.

    var l = Enumerator.Range(1,100).ToArray();

    for (var i in l[25:75])

     Console.WriteLine(i); //prints ints from 25 to 75

    including pythons start/end defaults

    l[:5];// the first 5

    l[96:];//the last 5

  86. SalizarMarxx says:

    Heres an off topic question. Recently the C++ team has released a beta of the upcoming MFC changes. Included in this are some nice UI changes that incorrorate alot of the Office/Visual Studio UI enchancements, such as docking, theming, Ribbon Bar, and more…

    Is there any plans to update WInForms to include these enchancements?

  87. wkhazzard says:

    I proposed the idea on this topic a while back of using the type inferencing available through the "var" keyword to support reflective, late-bound lookup. Now, we all know that "var" isn’t a type but the compiler could allow references obtained that way to bind late. For example, to reflect and find SomeUnknownMethod() at runtime, this would NOT be allowed:

    MyClass m = GetMyClass();

    // illegal b/c MyClass is not known

    // to implement SomeUnknownMethod

    m.SomeUnknownMethod();

    However, this would compile:

    var x = GetMyClass();

    // legal b/c var allows for

    // late binding on references

    x.SomeUnknownMethod();

    Being marked as "var", the reference x gets special dynamic treatment.

    I like this better than anything else I’ve seen here because:

    1. It is a simple extension of the type inference concept that already exists.

    2. It would force certain C# developers who might use "var" a little too often (if you known what I mean) to avoid the possible dynamic side effects introduced by this enhancement.

    –Kevin

  88. Paul says:

    What a terrible idea. It seems like we keep taking this circular path with languages that takes us back to exactly where we started, but with new toys.

    So much for type safety and code that can be analyzed by external tools for issues

  89. David Nelson says:

    @John Rusk,

    I can certainly see your point about dynamic calls being easier if the syntax is available in the language. However, I am VERY concerned about the long term effect this feature will have on the language. Much has been made in the past about new language features starting out with "minus 100 points" (http://blogs.msdn.com/ericgu/archive/2004/01/12/57985.aspx), and that they must prove that they have significant enough value that they can overcome the inherent negative impact that adding any new feature has on a language. I am far from convinced that this feature meets that criteria. I would like to hear from the language team what they think about that issue, as well as other people in the community.

  90. Una vez salidos al mercado .NET 3.5 y C# 3.0, el equipo de desarrollo ya ha comenzado a pensar en las

  91. Danilo says:

    I think the best approach is using a special operator like ..

    And how about constructing objects dynamically? Like:

    Type t = typeof(SomeClass);

    object dynamicObj = new t(10);

    -or-

    Type t = typeof(SomeClass);

    object dynamicObj = dynamic t(10);

    And then the runtime call the correct constructor and create the object.

  92. commenter says:

    So, the proposed block syntax might have two motivations that I can think of:

    * It’s for implementation/performance reasons. Some context will be built up and held within the block in order to perform the dynamic lookup. This can then be discarded when the block is exited. If this is the motivation then I think the syntax gets in the way of usage and any performance considerations should be ‘hidden’ and not emphasised in a block syntax.

    * It’s to deliberately demarcate dynamic lookup code so that programmers can see it being used. If this is the case then I can see the point. But at the same time I think it might make the facility too annoying to use by introducing variable scoping issues and mixing up static and dynamic lookup.

    My opinion is that dynamic lookup happens when you call a method/property/indexer on an object, so the syntax should be at that level, not at a block level.

    Thanks for publishing this blog post by the way, even if it has resulted in us all annoying you with our impractical suggestions. 🙂

  93. Alan Fox says:

    I welcome the prospect of being able to (easily) make late bound calls using C# and anything that makes COM/Office interop easier, without going the whole hog of introducing optional parameters into the languages, is particularly welcome in my opinion.

    Although I do have some sympathy with those who would prefer C# to remain wholly static, I think the time has now come where the language can afford to relax a bit on this and that, if it doesn’t, it may find itself losing popularity to languages which do.

    Personally, I’d like to see the day where I can do all my programming in C# – it may be asking too much but that would be my ideal.

    As this is going to be a .NET wide facility, I suppose the implementation which the C# team eventually settles on will need to be consistent with the DLR infrastructure but, if there’s any choice in the matter, I agree with most of the other posters that having a dynamic block is not the best solution.

    In fact if, as Charlie said, there is no reason to consider a dynamic variable as anything special, I see no reason to introduce a new ‘dynamic’ keyword or attribute at all!

    All you need is a special operator for dynamic lookup and a rule which says that this can be applied to any variable or expression of type System.Object but not any other type. The compiler won’t then check the call for correctness (except as potentially valid C#) and the onus will be on the programmer to get it right.

    As for the choice of special operator, I’m not keen on .. which looks like a range operator and I don’t like -> either because that’s currently used only for unsafe code. I’d prefer something different such as:

    objectExp~SomeMethod();

    which would stand out more.

    This will still make Office interop code very easy to write (with the help of Intellisense)and you won’t have to decorate all your COM object variables with ‘dynamic’ or include them in a dynamic block.

    It would in any case be difficult to use a common word such as dynamic as a new keyword (except perhaps as a contextual one) because it’s sure to break some existing code which hitherto the C# team have been almost paranoid to avoid doing.

  94. wkhazzard says:

    That’s pretty cool, Alan. I wish I had thought of that. 😉 Now, what happens when I do this?

    ===================================

    string X = "kilroy";

    objRef~SomeProp.SomeMethod( X );

    ===================================

    What about the reference to string X? Should the dynamic call be able to reach into the local, statically defined context like this? What about?

    ===================================

    Customer Z;

    objRef~SomeProp.SomeMethod( out Z );

    ===================================

    — Kevin

  95. Alan Fox says:

    That’s certainly what I’d like Kevin and I can’t really see why it shouldn’t be possible – the call, in it’s entirety, will either succeed or fail at runtime.

    However, given that the C# team have come up with this idea of a dynamic block rather than the (more obvious) ones of dynamic variables or a dynamic lookup operator, it makes me wonder whether we may be missing something here and that there are problems mixing dynamic and static contexts.

    You can’t really tell anything from the current implementation of late bound calls in VB.Net. If you set Option Strict to Off, the two examples you gave work fine but it appears that the whole context of the program is treated as dynamic. For example, even the following statement is allowed by the compiler:

    Dim i As Integer = "Hello"

    which is certainly not something we’d want to see in C#, however dynamic lookup is implemented.

  96. Ross says:

    If this is implemented, I am highly in favor of:

    dynamic object myObject = …

    instead of the dynamic block. Having said, that I’m not really sure that we really need this at all. Static binding is your friend.

    As for the Java suggestion earlier… the reason I like C# is that it IS like Java, except that it works correctly and isn’t horribly slow (which is largely due to the fact that it is NOT dynamic.)

  97. Roger Alsing says:

    >>dynamic object myObject = …

    Im voting for that approach too.

    Much better to attach the late binding to a specific variable than to a scope.

    It should also apply late binding to the result of a late bound call.

    eg.

    dynamic object foo = GetSomeObject…

    //traverse a latebound property path

    foo.bar.harr.harr (1,2,3);

  98. Octavio Hernandez says:

    Maybe require that all uses of the "dynamic call" operator (whether it is written as .., -> or ~) appear only WITHIN UNSAFE BLOCKS?

    After all, these are unsafe operations….

  99. David Nelson says:

    @Octavio

    Your suggestion makes a certain amount of sense, however, in C# unsafe blocks are used to indicate code that might produce unverifiable IL (as opposed to normal C# code which is guaranteed by the compiler to produce verifiable IL). So there are two different meanings for unsafe here, and they don’t really mesh well with each other.

  100. Σε συνέχεια του post περί late binding , ας δούμε πως μπορούμε να πετύχουμε σωστό late binding, χωρίς

  101. Simon Watfa says:

    The syntax dynamic object myDynamicObject = GetDynamicObject(); is the best suggestion so far.

    – The dynamic { … } code block is too coarse as many people have already said.

    – A dynamic object presumably would not have both, static and dynamic methods so why introduce a special dynamic call operator such as "..", "~", etc.?  Can anyone ever envision calling myDynamicObject.GetName() (a static method with one dot invocation) and then calling a myDynamicObject..SomeUnknownMethod()  (the two dots notation) on the same object?  Not likely, dynamic objects will almost certainly be composed entirely of dynamic methods.  If that is the case, then why introduce the extra calling syntax clutter?  There is a certain aesthetic beauty and elegance to consistency that ought to be maintained.  Ask C++ developers how they liked having two different calling operators in their language.  This ex-C++ developer says NO.

    – Those who think they can pre-declare interfaces on dynamic objects are forgetting that the objects are dynamic… ie. some languages allow methods to be added or removed from such objects at runtime.  Indeed some languages allow objects to be fleshed out with method sets determined completely by runtime conditions.  Take a look at look at the vast codebase of oo Javascript in use in the wild.  Take a lot at the latest Ajax or JSON libraries.  The whole point of Dynamic objects is that you can’t predict or know ahead of time what methods or properties they will possess at any point before you acquire a runtime reference to them.  As well, who in the heck would want to pre-declare some of the Office Automation objects before they use them?  Have you seen some of the interfaces on these things?  There are hundreds if not thousands of methods whose signatures you’d ahve to predefine.  Besides, why would you even do this instead of using the COM type library that ships with the interop assembly?  And this is describing a scenario of using COM objects who actually HAVE a statically defined interface to begin with.  Forget about all that if you are actually dealing with objects coming from a dynamic language.  Where pre-declared interfaces may be of use if one is using only a limited set of functionality on an incoming dynamic objects and wants to impose a statically bound interface on the interesting subset of methods.  In this case, the interface acts as an intellisense-friendly facade to the underlying object which may in fact possess a much larger set of uninteresting or undesired methods.  In this case, the runtime would have to enforce that there exists a way to coerce the underlying object to map onto the pre-declared interface. ie. All the pre-declared method signatures would have to have matching methods in the underlying object.

    – For those who are concerned about C# straying from its statically typed roots, no need to worry.  No one here is saying that C# will be equipped to MAKE dynamic objects, but rather CONSUME them… and given that, then what is the objection?  Why not open the door of possibilities to using all that code in the wild from within C#?  Doesn’t seem to detract from the attractiveness and utility of the language one bit.  If you are still ideologically opposed to this, then the answer is simple:  just make sure you never use libraries that are created in dynamic .Net languages (like Python or Ruby, etc.)  Simple.  We can all live in peace and harmony.

    In summary, my vote is for:

    dynamic object myDynamicObject = GetDynamicObject();

    NO to dynamic { … } code blocks, and NO to special dynamic call operators.

  102. I would like the .. operator 🙂

  103. First, thanks for discussing future features with the community!

    There is another scenario where a ‘dynamic’ keyword would be useful: in constraints on generic types. I would like to be able to say

    public class Matrix<T>

      where T: dynamic INumeric

    {

    }

    Matrix<double> x = new Matrix<double>();

    In this case ‘double’ does NOT implement our hypothetical interface INumeric, but if it has all the methods required by that interface, the compiler will allow the generic object to be created.

    This is all static and the compiler should object if it can’t verify the interface at compile-time.

    Such constraints are what’s missing in order to make C# truly great for numeric/scientific computations. Other scenarios include treating objects as collections even if they happen not to implement IList, etc.

    /Sten

  104. C# nelle future versioni di Visual Studio

  105. Justin Chase says:

    I would like to request the ability to coerce anonymous types into interfaces. So you can use LINQ for more than just databinding, so you can actually return strongly typed objects from any method without having to declare all of your types. Something like:

    public IExample[] GetExamples()

    {

       return (from e in examples select new IExample { P1 = e.Text }).ToArray();

    }

    If you had methods on the interface than either create an empty method that returns the default value or allow delegates to be attached to the interface at creation time.

    maybe like:

    public IExample GetExample()

    {

      return new IExample { P1=this.Text, Run=this.RunExample };

    }

    private void RunExample()

    {

       //do some stuff here.

    }

  106. Tom Tucker says:

    I think they need dynamic types in C# because the other dynamic languages dont use the C style syntax(at least not popular/useable ones)

    Second-

    It sure would be nice to have some more dynamic behavior with Generic types even polymorphism. And while I am at it throw in interface property attributes recognizeable as [Column] in Linq so you can use linq more dynamically/genericly as well.

  107. C# is a changing language. C# 1.0 was all about core component-support. With C# 2.0 generics have been…

  108. ccalvert says:

    I feel like I haven’t had a chance to respond to comments in the last few days. As a result, I wanted to take a moment to assure everyone that we have been reading these comments, and that the design team has seen them, and has taken them seriously.

    It’s perhaps worth reminding everyone that our goals here are twofold:

    1) We went to be open and share our plans with the community.

    2) We want to absorb your feedback and make good use of it.

    Looking at those two yardsticks as a way of measuring our progress, I would say that this has been a very successful process for us. It is great to be able to share ideas with the community, and your input has been very useful to us. We are not yet ready to say exactly how these comments have influenced the team, but I can assure you that they have influenced us, and they have had a positive impact on our planning process. Thank you so much for the comments you have submitted so far.

  109. David Nelson says:

    @Charlie,

    Why do I get the feeling that you are trying to prepare us for the fact that even after all of the feedback you have gotten from this blog, you still decided to go with your original dynamic block idea?

  110. David Nelson says:

    @Simon,

    "A dynamic object presumably would not have both, static and dynamic methods"

    For objects instantiated by a dynamic library, you are probably right. But imagine if you want to use dynamic method invocation to invoke a method declared as private in a statically defined class using reflection? In that case, it is certainly possible to imagine cases where you might want to make both static and dynamic calls on the same object; and at that point, a dynamic call operator might make sense. Not necessarily voting in favor of it, just pointing out that it is not as ridiculous as you made it sound.

  111. Alex Klikouchin says:

    I’ve read all comments, and I vote for this:

    dynamic object a = GetDynamicObject();

    a..SomeMethod(x);

    a.ToString();

    a..SomeProperty = "123";

  112. ccalvert says:

    David,

    I want to assure you that the design team has been actively engaged with this process and is really grateful for your input and has found it very interesting and helpful. Our goal is to be open and to share information freely, and of course we actively gather feedback for the design team.  If you reread the initial paragraphs of this post, you’ll see why I don’t want to promise specific outcomes, nor allow myself to set expectations too high. I promise that the comments that have been made here have been and will continue to be carefully monitored by myself and the design team. I can also promise that your comments are having a real and positive impact. They aren’t being ignored. They are actively and sometimes heatedly discussed. The design team has been interested, excited, and engaged by the input you and others have given. This process has been a success so far, and that means we want to do much more of it. We all appreciate the intelligent and courteous feedback we have received, and we are very happy about its success.

    – Charlie

  113. MSDN Archive says:

    Love the idea, but the dynamic keyword is indeed a bit limiting – since it’s most logically tied to an instance, the "this is dynamic" magic should be tied to an instance/variable instead of a scope.

    What Andrew Davey said about IQuackFu from Boo is good, but IMHO the easier and more powerful approach is also from Boo – the "duck" type (http://boo.codehaus.org/Duck+Typing), which you declare a variable as and then the compiler knows that it’s a dynamic type.  Then you can pass "duck" objects around without having to deal with the dynamic keyword.  Then tools (like the debugger) also know the instance is "special" and interact with it as such.

    Instead of duck, though, perhaps System.Dynamic or similar, since it probably makes sense to have it represented in the BCL since you may want to string some static methods off of the type (System.Dynamic) that helps runtime interaction with such objects, like easier-than-reflection inspection of methods/properties/etc, or Ruby’s "reopen this instance/the entire class" support, or whatever.

    Back to the IQuackFu/IDynamicDispatch idea – as long as the compiler implements it as a fallback so "regular" method calls that are implemented by the type keep working as normal, then that’s fine with me – it’s effectively Ruby’s method_missing at that point, which would be useful to have in some situations.

    The combination of the two gives you both fully-dynamic instances (with the duck typing aka System.Dynamic) and partially-static, partially-dynamic (with IQuackFu aka IDynamicDispatcher), so you can choose what works best for you.

    The idea is great, but I really fear the dispatch keyword+scope approach would make it less useful (read: more cumbersome) to interact with.

  114. Ok, so it’s just in the planning stages, but you may have run across Charlie Calvert’s recent blog post

  115. VB6 and VB.Net developers know this feature: &quot;Late Binding&quot; and C# developers have often ridiculed

  116. Ok, so it&#39;s just in the planning stages, but you may have run across Charlie Calvert&#39;s recent

  117. Allen Bauer says:

    Hey Charlie!

     You, of course, remember that Delphi has also had this same functionality since version 3 (10 years ago) by using dynamic Variant dispatching.  In natively compiled code, no less.  I’m just saying… 😉  The cycle is coming around again…

    Say ‘Hi’ to Anders, Chuck and the whole gang for me!

    Allen.

  118. Ron Buckton says:

    Charlie, Mads;

    I definately like the idea of adding some dynamic typing support for C#.  I’ve seen a lot of comments on various ideas for implementation and wanted to throw in my own.

    Using ‘dynamic’ as a block is a good idea that seems to cause usage problems when defining initial values (such as in field member declarations).  While this can be resolved by placing a dynamic {} call in the ctor or cctor you might also provide a dynamic() keyword (similar to the unchecked{} vs unchecked() syntax).  This would allow you to do the following:

    class MyClass {

     object foo = dynamic(SomeStatic.GetSomeDynamic().someDynamicMethod);

     void Method01() {

       dynamic {

         foo.Method01();

       }

     }

    }

    I would also recommend allowing the ‘dynamic’ keyword be applied to a method or type similar to the ‘unsafe’ keywoard, informing the compiler to widen its usage of the DLR based on the scope of what is dynamic (type, method, get, set, add, remove, and at the expression level).

    The key here I’m seeing is that C# is *not* a dynamic language and should not become one, but by adding a dynamic{}/() language feature merely lets you call into the dynamic language aspects.

    Dynamic is also useful in a LINQ scenaro, e.g.:

    void Foo() {

      var q = from o in GetData()

      where o.State = "WA"

      select new { CustomerCount = o.Count, … }

      foreach(var r in q) {

         print(dynamic(r.CustomerCount));

      }

    }

    I also think adding in some type of interface based manipulation of the dynamic context without the expense of having to use a RealProxy would be useful as well.  In addition, it would be useful to be able to test for the existance of a dynamic field, method or property before a call using a "has" keyword followed by a signature (matching a method, field, property, or event signature), e.g.:

    dynamic void Foo(object bar) {

      if (bar has void Baz()) {

         bar.Baz();

      }

      if (bar has string Text { get; }) {

         print(bar.Text);

      }

    }

    I also think the idea of supporting dynamic instantiation of a type by overloading the new operator:

    /*

     new StaticTypeName(); /* standard new */

     new { PropI = 1, PropS = "2" }; /* anonymous type new */

     new (typeInstance); /* new using argument of System.Type */

     new (progid="Some.ProgID"); /* new using a progid */

     new (clsid="SOMEGUID-00ad-00ad-0a0a00…"); /* new using a CLSID */

    */

    void Foo(Type t) {

      object f = dynamic(new (t));

    }

    dynamic void Foo() {

      var x = new (progid="MSXML2.DOMDocument");

      x.loadXML("<foo/>");

    }

    The key here is that complicated reflection calls can be pared down to simple keywords, which could take the guesswork out of reflection.

    Also if dynamic is effectively a compiler macro over reflection, it might be useful to be able to mark certain dynamic calls based on binding flags, e.g.:

    class Foo {

     private int bar = 1;

    }

    Foo f = new Foo();

    int bar = dynamic(f.bar, private);

  119. David Nelson says:

    Charlie,

    I can certainly appreciate that you cannot promise any specific outcome. I can also appreciate that sharing these plans with the community does not mean that this is our chance to design the feature; the inmates cannot be allowed to run the asylum, as it were.

    I suppose I am simply wary because I have seen this too many times before. A team decides on a new feature it wants to implement, debates it internally, and comes up with the approach they want to use, and then exposes that approach to the community. At which point, there is a very strong community response toward another approach, or away from the feature entirely; but at that point it is too late, because the team has already convinced itself of "the right way" to do it.

    I can only hope that will not be the case here; what prompted my comment was that, although the tone of your comment was positive, I felt it ringing with an undertone of "but don’t get your hopes up." Which, as you say, you had already stated earlier.

    Please don’t let my pessimism or cynicism dissuade you from continuing the series. I would love to see what else the team is coming up with, even if I don’t get to do it the way I want 🙂

  120. Dave says:

    This will become very handy for mine MVC RouteProviders in SQL en XML. Now I have to use dynamic compiling to create a structure to pass the parameters which are normally build as

    new { Controller="HomeController", Action="View", ID="ObjectID" } and passed to the MvcRouteHandler as an ‘Object’

    The compiler creates a anonymous typed when compiling, but you can’t yet create really dynamic  structures.

    Sounds very promising..

  121. Sebastian Ferreyra says:

    Regarding type safety, I believe it’s good to limit the dynamic keyword to a variable declaration. But also, it shouldn’t be limited to ‘dynamic object’ we should be able to declare dynamic variables of any interface type.

    Even on dynamic objects programmers know pretty well what to expect, but this way the compiler catches typos.

    Example:

    interface IMyCOMAPI

       {

       void MyMethod();

       int CalculateSomething(int someParam);

       }

    dynamic IMyCOMAPI myO = GetDynamicObjectFromSomewhere();

    myO.MyMethod(); //just fine!

    myO.NyMethod(); // hey!! a typo!

    I think that resolves many issues elegantly.

  122. Sebastian Ferreyra says:

    Perhaps I should add …

    ‘GetDynamicObjectFromSomewhere()’ would be the only place where a binding related runtime excpetion would occur.

    Optimizations, like caching reflection objects, would be done in an anonymous class that implements the interface and actually takes care of the binding.

    This way optimal use of a dynamic object can be planned by developers. Like initializing dynamic objects once, automatically binding upon construction, sotring it in a field, and invoke methods efficiently throughout the field’s scope thanks to this.

    Well, my 2 cents …

    Sebastian

  123. Sebastian Ferreyra says:

    Sorry, on a roll …

    Another benefit I just noticed (although I can see some criticism) of this method is that by using itnerfaces, we can pass dynamic objects to all consumers of the interface, even those that were not initially devised for dynamic object consumption (assuming we use a predefined and already popular interface). This is were the possible criticisms arise, because although everything except binding can can be statically checked, the potential remains for misuse.

    I however think compilers are there to protect us from typos and similar mistakes, not from not understanding and API.

    Sebastian

  124. Sebastian Ferreyra says:

    Hey, me again heh,

    It’s later in the day and I realized the following: There doesn’t need to be a ‘dynamic’ keyword at all. All that’s really needed is a way to wrap dynamic objects in anonymous interface implementations.

    For COM:

    A dynamically bound COM object could be created by a generic (as in generically typed) COM object factory.

    Example:

    interface IMyCOMAPI

      {

      void MyMethod();

      int CalculateSomething(int someParam);

      }

    IMyCOMAPI myO = new DynamicCOMObject<IMyCOMAPI>(guid /*or pointer to object or whatever*/);

    myO.MyMethod(); //just fine!

    myO.NyMethod(); // hey!! a typo! compiler detected as always

    For the DLR and its dynamic objects:

    The DLR can return dynamic objects, like it normally does, which will be dynamically bound to an interface at the developer’s will.

    Something like perhaps:

    object o = dlrObject.GetDynamicObject();

    IMyCOMAPI myO = DLR.BindObject<IMyCOMAPI>(o); // no special operator ever needed.

    Perhaps I’m missing something? some feature? It doesn’t seem like an operator is needed at all.

    Sebastian

  125. wekempf says:

    First, for those that don’t want dynamic features in the language, get over it or stop using C#, because what’s being proposed already exists.  The suggestion to move to Java doesn’t help, because it exists there as well.  In both, the feature is known as reflection.  The only difference here is we’re proposing language syntax to make it easier to accomplish.  Now, if you’re one of those that doesn’t care for syntactic sugar, then make that argument.

    I strongly believe our best bet is a new operator for this.

    void DoSomeDynamicStuff(Type type)

    {

      // reflective construction

      object instance = new type!(10);

      // non-reflective usage

      if (instance.GetType() != type)

          throw InvalidOperationException();

      // reflective method call

      instance!DoSomething(20);

      // reflective field/property access

      int result = instance!Result;

    }

    The ".." syntax would work as well, but I believe the "!" syntax is superior ;).

    This syntax makes the granularity as small as possible, which is best, IMHO.  It also makes every call explicit to both the compiler and the developer(s).  You always know if something is static or dynamic.

  126. Vasiliy Zharkovskiy says:

    This Dynamic are direct runaway from strong typification, but the last concept is foundation of C#.

    We need other higher-order approach for this problem.

    I think, we must to proceed from strong typification

    as basic.

    Simple Example (WSH inline):

    // There is begin of example——————–

    using System.Scripting.WSH;

    string StringBox = string.Empty;

    // in the next scope provides other (read: dynamic) rules

    script (WScript ws)

    {

      …

      exl = ws.CreateObject("Excel.Application");

      StringBox = exl.SomeMethod();

      …

    }

    // There is end of example———————-

    P.S. Sorry for my English. I am russian developer.

  127. FKruesch says:

    It would be nice to have more flexibel operator overloading, like arbitrary operators instead of a fixed set.

  128. James Swaine says:

    Aren’t you basically just adding VB-style late binding to C#?

  129. ccalvert says:

    I wanted to thank everyone again for their great suggestions. The positive and thoughtful nature of your feedback is greatly appreciated.

    We are now certain enough of our plans to confirm that your comments will lead to significant changes in the way we implement this feature. We are looking forward to the time when we can get back to you with concrete information on the exact nature of our new plans.

  130. The success of the first Future Focus post has made it easy for us to continue sharing our plans for

  131. zzz says:

    Well since we’re throwing random ideas about I’d like to join:

    There’s already extension methods but they do seem a bit limited in some ways so what about ‘extended scope’:

    !dynamic,with(GetDynamicObject())

    {

    .SomeMethod();

    .someString = "value";

    [0] = 25;

    }

    The only new keyword here is "!" for marking beginning of extended scope that brings in different entension delimited by ",".

    Now of course bringing a ton of weird extensions would likely always mean throwing away intellisense atleast in v1 but maybe if it proves popular some support could be added to add some intellisense features even in extended scopes.

  132. zzz says:

    "So much for type safety and code that can be analyzed by external tools for issues"

    That’s a very good point.

    The "infered duck typing" suggested above seems like a good idea without going overboard like the extendable scope thing which practically would mean a language in language.

  133. Troy Howard says:

    I agree with the duck typing concepts, but I suggest you simply extend the functionality of the as keyword.

    interface IDuck

    {

       // returns the string quack;

       string Quack();

       // moves the duck the specified number of steps, and returns the new location of the duck

       Point Waddle(int steps);

    }

    // note that this class does not implement IDuck specifically.

    class RandomFowl

    {

       public string Quack()

       {

           // … implementation

       }

       public Point Waddle(int steps)

       {

           // … implementation

       }

    }

    then you can use it:

       RandomFowl fowl = new RandomFowl();

    // here the as operator infers that the RandomFowl object is compatible with IDuck, since it implements the required method.

    // there is no need to specify that this is a "dynamic lookup" behaviour.

    IDuck duck = fowl as IDuck;

    if(null != duck)

    {

       duck.Quack();

           Point location = duck.Waddle(10);

    }

    Lets go farther… What might also be interesting are anonymous interfaces… like:

       interface duck = fowl as interface {

           string Quack();

           Point Waddle(int steps);

           };

       if (null != duck)

       {

           duck.Quack();

           duck.Waddle(10);

       }

    Even better would be anonymous interfaces with the ability to specify failover implementation.

       interface duck = fowl as interface {

           string Quack() : { return "Quack"; };

           Point Waddle(int steps) : { return Point.Empty; };

           };

       if (null != duck)

       {

           duck.Quack();

           duck.Waddle(10);

       }

    So what you get with that, is something like if the class had inherited a base class with the methods Quack and Waddle implemented as virtual methods. If the class implements them, that implementation is used, userwise the interface failover definition is used… Even better if type constraints could be applied in that failover implementation.

    Here’s a more realistic example, showing type constraints in an anonymous interface with failover implementations:

    class Person

    {

       private string _name;

       public string Name

       {

           get { return _name; }

       }

    }

    class Thing

    {

       private string _description;

       public string Description

       {

           get { return _description; }

       }

    }

    static void PrintDescription(object obj)

    {

       interface describableObject = obj as

           interface {

               string Description

               {

                   get :

                       switch (this.GetType())

                       {

                           case typeof(Person):

                               { return this.Name; };

                               break;

                           default:

                               { return this.ToString(); };

                               break;

                       }

               }

           };

       if(null != describableObject)

       {

           Console.WriteLine(describableObject.Description);

       }

    }

       List<object> someObjects = new List<object>();

       Person person = new Person();

       person.Name = "Bob";

       Thing thing = new Thing();

       thing.Description = "Piano";

       SomeOtherType foo = new SomeOtherType();

       someObjects.Add(person);

       someObjects.Add(thing);

       someObjects.Add(foo);

       foreach(object obj in someObjects)

       {

           PrintDescription(obj);

       }

    Output would be:

    Bob

    Piano

    SomeOtherType

    In the case of the Person instance, it couldn’t find a matching Description property, so it went into the failover implementation which contained a switch block, that checked the type of the object instance, found it to be a Person type, and used the implementation specified in that case block. The Thing instance had a Description property already, so it just inferred the anonymous interface, The SomeOtherType instance didn’t have a Description property, or a failover description defined, so it used the code in the default case block. Leaveing out the default case block here would have caused the cast to the anonymouse nterface to fail, and describableObject would have been null.

    Maybe these ideas aren’t practical, but I think they would be useful, and fit nicely with the existing langauge features, without compromising type safety.

    Regarding syntax used… Using the colon to indicate failover implementation makes sense to me, since colon is used in the terniary expression syntax (ie: " (bool) ? true : false; "). Also, using switch case for the type constraints is a little verbose, and could probably be done more like the generic type constains, though, to be honest, those need a lot of work too.

    I personally think using existing keywords is a much better idea than adding new ones. for example, using the default(Type) syntax was a great idea. Please don’t add any new keywords.. Just find a way for it to make sense with the existing ones.

    Thanks,

    Troy

    thoward37 at gmail dot com

  134. Kaveh Shahbazian says:

    Will C# have syntax extension macros? It is a well known practice in Lisp world. In .NET there are some successful implementations like ones in BOO ans Nemerle. Of course what BOO and Nemerle provides are different than Lisp ones; yet they are very usefull tools. Those syntax extensions are type-safe. Is there any plan to implement that in C# 3.5 or 4.0?

    (There are many other features that I like to have in my C# toolbox. Yet this one is the most important one to me and many of other features that I like to have; can be implemented easily via a stable well-designed macro system.)

  135. @ Head says:

    Kudos to Charlie Calvert for opening up the discussion of C# future features to the public (sure would

  136. anon says:

    Hopefully the dynamics includes also the following syntax:

    string method = "MyMethod";

    object.method();

    or directly:

    object."MyMethod"();

    or some other new syntax to accomplish the above.

    Otherwise it’s not really dynamic, i.e. you have to know the method names when you write the code. Runtime resolution of the method name should be possible like with reflection.

  137. Troy Howard says:

    @anon: you said, "Otherwise it’s not really dynamic, i.e. you have to know the method names when you write the code. Runtime resolution of the method name should be possible like with reflection."

    Either way you need to know the method name when you write the code.. But you’re right, it’s not "dynamic", and that’s kind of a silly word for it. It’s "runtime method reoslution".

    They are using the word "dynamic" in this context to mean that even though you know the method name and parameters that you want to call, the object may or may not actually have it at that point. The reason it’s being referred to as dynamic is because the intention is to use this feature to deal with dynamicly typed objects.

    So what is dynamic?

    Currently, we describe what methods we want a type to have using static type declaration. That means that once you’ve defined the type, you can’t add more methods or properties to it, or change it at all. In order to make changes, you need to make a new type. Those two types will be "different" all the time, no matter how similiar they are.

    With dynamic typing, the type itself can be modified at runtime.

    What they are discussing here is a "dynamic" lookup of the methods on a type. For example, normally, when you write:

    someObject.someMethod();

    The c# compiler will check the type of object *when you compile* to make sure it has the method "someMethod". If it doesn’t have that method, it won’t compile, and will generate an error.

    The "dynamic" concept we’re discussing is to allow you to write (using your syntax):

    someObject."someMethod"();

    to indicate that, while the method may not be there when I compile, it will probably be there when the code is running, because the type "someObject" is a dynamic type, whose methods and method names may or may not be consistent.

    In that context, we’re telling the compiler "don’t check the method name now, wait until runtime, and do a ‘dynamic lookup’ of the method on the type, and if it’s there, invoke it with these parameters."

    This is definately something that can be accomplished with Reflection, in the sense that you could write a DynamicMethodInvoke method that took an object instance, method name, and a list of parameters, and it would call GetType() on the instance, then GetMethod() on the type, passing GetMethod the methodname, and the parameter’s types in an array… That would return a MethodInfo for the oject, if it was there, then you could call Invoke() on the MethodInfo object, passing the parameters..

    For some reason, Microsoft wants to make this part of the built-in syntax of the language. Probably to make it easier and more convienent for people to do that, instead of forcing them to write the described Reflection code a million times. It could easily a extension method, but then, the code would be really ugly if every call you made on a dynamically typed object had to be made like this:

    dynamicObject.DynamicInvoke("Foo", new object[] { some, parameters, go here } );

    So, implementing this as a language features is a nice idea, and the syntax you described would work fine for that.

    Anyhow, it’s important to understand that this is not in anyway bringing dynamic typing into c# syntax, but rather allowing c# to deal with dynamic types that are already in the .Net universe.

    The way I described this, was to use interfaces. Interfaces allow you to specify the function prototypes of method on an object.

    Wether you’re using interfaces, delegates, or just regular methods on a class, you’re doing fundamentally the same thing. You’re describing a method by name, and a list of parameters, and you’re indicating an object instance that you want to invoke it on…

    Consider these three different ways of running the method Bar():

    class Foo

    {

     void Bar();

    }

    interface IFoo

    {

      void Bar();

    }

    ((IFoo)object).Bar();

    delegate void BarDelegate();

    class Foo

    {

     void MyMethod();

    }

    Foo foo = new Foo();

    BarDelegate bar = new BarDelegate(foo.MyMethod);

    bar.Invoke();

    So, in short, all we really need is to indicate, in some way to the compiler that it shouldn’t check the static type definiton of the method call described by your code at compile time, but rather, emit code that lookup the method at runtime.

    I like interfaces, because it is a concise way to describe a set of methods and thier signature that I can use as a single atomic check.

    The downside in C# now is that if a type doesn’t implement an interface at compile type using the "Foo : IFoo" syntax, then, even if the type has all the necessary methods to comply to an interface, there is no way to "apply" the interface to it after compilation. This is known as "duck typing" (ie. "if it looks like a duck, walks like a duck, and sounds like a duck…. it’s a duck!").

    I would like to be able to apply an interface to an object at runtime. I would also like to be able to describe the interface I want at runtime, "anonymously", and give default method implementations if the type does not implement a given method.

    Thanks,

    Troy

    thoward37 at gmail dot com

    PS: Somebody please correct me if I misspoke. I don’t have a debugger in the blog comment textbox… 😉

  138. Pop Catalin says:

    I’d say to still preserve type safety even if it means a litle more typing to declare dinamic method signatures beforehand.

    In my example, the result of GetDynamicObject() is casted to an anonimous type specifiong the methods that should be bound, and if the binding fails null is returned.

    var someObj = GetDinamicObject() as new {String Text, void Foo(int x)};

    if (someObj != null) {

      someObj.Text = "Bar"

      someObj.Foo(6);

    }

    and you can do even more:

    interface IBar {

      int SomeMethod(int param)

    }

    var someOtherObj = GetDinamicObject() as new {String Text, void Foo(int x)}:IBar

    the cast will only succed if the object returned by GetDinamicObject() implements IBar and has a public ‘String Text’ property and a public ‘void Foo(int x)’ method.

    if (someObj != null) {

      someObj.Text = "Bar"

      someObj.Foo(6);

      someObj.SomeMethod(3);

    }

    Maybe if the cast fails, it’s not null that should be returned but, an UnboundDinamicObject instance that has null equality and should throw UnboundCallException when someone tries to do a dinamic call whithout checking for null, but this could have some issues regarding an Object.ReferenceEquals(someObj, null) call.

    My opinion is, late binding is ok as long as it doesn’t compromise type safety and adds the posibility to introduce type and spelling errors in staticaly type cheched language like C#.

  139. Ted says:

    I certainly hope I will be able to turn this "feature" off for our in-house developers.

  140. sergsams says:

    Sorry for my English!

    I think that one of ways for creating dynamic classes is like this:

    using System;

    class A

    {

     static void Main()

     {

       string s="class B { "

                +"  public void DisplayMessage() { "

                +"    Console.WriteLine("Hello from dynamic C#.");"

                +"  }"

                +"}";

       dynamic B obj = new B(s);

       obj.DisplayMessage();

     }

    }

    Reason is:

    1)Possibilities to create varible s dynamicaly and then create class dynamicaly.

    2)Posibilities to read existing cs files and after modification create new classes dynamicaly.

  141. Its not big deal. Well its good to hear that "dynamic" would be a built-in feature for C# developers (too).

    I have already done this sort of work by writing my own classes using reflection. And really it worked some how the same way.

  142. Emil says:

    Please don’t turn C# into a dynamically typed language…

  143. Peter V. says:

    Let me add my name to long list above opposing this.

    I use C# primarily because I can depend on it being type safe by default. Dynamic lookup will destroy this. Can I disable the feature? In a team environment, I would hate to think about manually checking for this abusive code.

    Further, as already mentioned, this type of functionality belongs in a library, not at the language level…

    Please reconsider this. Whether you realize it or not, you’re destroying C#.

  144. Halo_Four says:

    I would think that something like this would be better accomplished through the DLR than through new syntax and type semantics in the C# language.  As others have mentioned, a lot of us like C# because it is explicitly type-safe and we can assume that it will always be so.  Anytime I need to interact with COM classes in a late-bound fashion I always use VB.NET and isolate that code from the rest of the solution.

    My personal preference would be a method off of the DLR, or within the CLR, to allow an arbitrary object to be duck-typed to a specific interface.  That method would perform the necessary inspection to ensure that the object members can be bound to the interface members and a proxy type that implements the interface it returned.

    public interface IRecordset {

       void Close();

    }

    object rs = GetRecordsetFromSomewhere();

    IRecordset irs = DLR.DynamicCast<IRecordset>();

    irs.Close();  // wouldn’t we all like to do this?

    I think that while being more verbose that this enables the scenario without trading type-safety.

    I really don’t want C# to end up with something akin to Option Explicit or Option Strict.

  145. David Nelson says:

    I really, really like Halo_Four’s solution. It keeps C# entirely in the static typing world, doesn’t require any new language features, but still gives us everything we are looking for in terms of making dynamic calls, both reflecting to the internals of an object and calls on dynamic objects. The only downside is that it requires an additional interface to be defined; but that can be a good thing, because that interface now exists in the metadata, and can be used like other type definitions.

    Charlie, what do you think?

  146. Edgar says:

    That’s a very interesting article, and I can easily see places where dynamic typing might be useful.  Have you guys looked into how ActionScript 3.0 deals with dynamic typing?  I think they came up with a really elegant solution for dynamic typing.

  147. Robert says:

    I second to David, Halo_Fours solution is an safe and elegant way to do it. I have used the dynamic lookup in Delphi (with variants) but never really liked it because it is prone to typing errors. Following syntax would defentely be better:

    dynamic interface IDog

    {

     void Run();

     void Eat();

    }

    ….

    object o = LetThereBeDog();

    IDog dog = (IDog)o;

    dog.Run();

    dog.Eat();

  148. Varun Sindhu says:

    That’s a very interesting article, and I can easily see places where dynamic typing might be useful.  Have you guys looked into how ActionScript 3.0 deals with dynamic typing?

  149. Jan Kučera says:

    Hi,

    thank you for sharing you current plans.

    I’ve read through the comments, and saw some pretty good ones, yet also very bad ones.

    I don’t think it is bad to get feature from other languages into the existing one, unless it influences anybody who does not want to use it.

    So:

    – Do not mix it with var keyword. It is strongly typed, safe type. Any attempt to use it for dynamics would make all the people against var having actually truth.

    – Do not mix it with interafaces. Interfaces are what they are for and taking them into dynamics makes the interface concept more complex, and turns dynamics into generics. Dynamics should just turn your calls into reflection ones. That’s it, no interfaces. If anybody wants to wrap the dynamic object into class, why not.

    – Do not restrict the base dynamic object to the type of object. Dynamics should not force you to cast to object if you know the base type.

    – Make sure you can get anything you would need to do using reflection. Access static members, generic ones, etc. I agree with the suggestion of calling constructor dynamically as well, instead of kind of GetDynamicObject() method.

    – As far as the scope is mentioned… it seems you could fulfill wishes of peoply only if you allowed both object and block scope. I don’t think any keyword is needed at all, if you make the member accessor different. From what I’ve seen I like most the .. one, though I still do not feel 100% comfortable with this due to the .ctor and ..ctor methods. If you use special accessor, then no scope is needed, the behavior would be absolutely predictable (no attemps to early bind if the accessor is used) and the code would be much more clear.

    – Do not allow dynamics to access non-public members. This is not the purpose of dynamics and developers should still have to use reflection for this.

    If you make indexed properties also accessible, I would welcome them in static C# as well. 😉

    I believe you will get this as right as you want and wish you to ship it as good as you wanted.

    Jan

  150. Justin Chase says:

    Here are some thoughts I have regarding the ideas of dynamic method calls in C#:

    http://www.justnbusiness.com/Blogs/CSharp_Optionally_Dynamic_Calls.aspx

  151. Artur Mustafin says:

    I can agree with all written above, just because all of the statements have reasonablу meaning…

    I think we shoudn’t use the sugar.

    So, in my POV, i will use intensively code like this, which is IMHO actually do not loose meaning of word ‘simplicity’.

    It is my vision – i’d better appreciate to not thouch the language, but add compiler-generated stuff, and make a good support on a CLR, Frameworks and IDE;

    class A

    {

    //Compiler throws an exception when

    //DynamicObject type is used in places not

    //marked as DynamicMethod or DynamicProperty

    [DynamicObjectAttribute("Company")]

    object a;

    [DynamicMethodAttribute]

    int Foo(int typedA)

    {

    //DynamicObject is appears to users

    //as concrete, non-instantiable, sealed

    //(and so, non-derivable by users)

    //ancestor class of System.Object class.

    //Compiler treats all dynamic variables

    //as derived(and, so, hidden from users)

    //classes from DynamicObject class.

    if (a.GetType() == typeof(DynamicObject))

    {

     try

     {

       // Compiler-genarated call would be like

       //a.get_method<void, string>("SayHireMe")

       //using some sort of late binding

       if (((Action<string>)a.SayHireMe) != null)

       {

          //Already fail-safe call

          a.SayHireMe("Hello, World!");

          //Not so safe, i need more money:$1000000

          a.SayGoodBye(-1000000);

          a.SayGoodBye("Hello, World!");

       }

     //Intellisense analyses the usage of

     //object of type codename "Company"

     //and show both methods already used

     }

     catch(DynamicException)

     {

       try

       {

          MethodInfo[] mi = typeof(a).GetMethods();

          if (mi["SayGoodBye"] == null)

          {

             Console.WriteLine("You can’t say goodbye to your comany in such the way due to the fact, that object [Company] has no such a method, just because otherwise it will give you the possibiliby that you can not refuse. P.S. ‘And give us $1000000 back!’");

          }

          else

          {

             //checking in/out parameters…

          }

     }

    }

  152. Tony Valenti says:

    That’s pretty cool, however, have you though about making it so that the "dynamic" isn’t a scope keyword but instead applies to a variable?  Like this:

    dynamic object myDynamicObject = GetDynamicObject();

    myDynamicObject.SomeMethod();         // call a method  

    myDynamicObject.someString = "value"; // Set a field

    myDynamicObject[0] = 25;              // Access an indexer

    -tony V.

  153. omot vincent says:

    exellent,plz include me in the program.

    iwill be glade if you sent me more regarding C#.

    nice time

  154. Halo_Four says:

    Allow me to refine my suggestion a tad.  I wanted to clarify what I had intended as well as correct a minor problem with my sample.  As mentioned I don’t think the semantics of C# should be changed to support dynamic dispatch.  I would prefer a more intentional method of interacting with dynamic types.

    My suggestion is to not modify the language at all.  Instead, provide the facility through the DLR or through remoting to construct a proxy for an object given a defined interface.  That proxy would handle the details of how the actual members are called and would handle .NET objects as well as COM objects to the best of it’s ability.

    public interface ICalculator {

       int Add(int x, int y);

    }

    static void Main() {

       object o = GetCalculatorFromSomewhere();

       ICalculator calc = o.TryDynamicCast<ICalculator>();

       if(calc != null) {

           int value = calc.Add(2, 3);

       }

    }

    Extension methods would be provided through the DLR that would construct the proxy.  Suggestion methods as as follows:

    // Try to create proxy for interface T, throw exception if object cannot conform to interface

    public static T DynamicCast<T>(this object o);

    // Try to create proxy for interface T, return default(T) if object cannot conform to interface

    public static T TryDynamicCast<T>(this object o);

    // Return whether or not object can conform to interface

    public static bool CanDynamicCast<T>(this object o);

    Or the methods could just be normal static methods.

    What I like about this suggestion is that:

    1.  It does not change any semantics of C# at all.  Only normal run-of-the-mill interfaces are used and C# remains completely type-safe.

    2.  No language enhancements are required, so this functionality could be built right now on the existing C# 2.0/3.0 languages, depending on whether or not extension methods are used.

    3.  You gain the requested functionality of allowing "duck-typing" in C# automatically.

    4.  You only need to do this work in one place and any CLI-compatible language can immediately benefit since you are only using the existing facilities within the framework.  This will increase the pervasiveness of support for dynamic dispatch.

    The disadvantage is that this method is more verbose since you have to declare the interface, but it is my opinion that requiring the intent to be declared keeps the language appropriately type-safe.

    Also, it would prevent a dynamic object from being partially conformant to the requested interface.  I can envision problems with dynamic dispatch using a "dynamic" keyword where the consumer needs to make several calls and some of those calls exist and others do.  The code necessary to compensate could be complicated.

    Anyway, I hope you consider my recommendation.  In fact, I hope you can see it at all buried in the slew of comments on this article.

    Thanks,

    Justin

  155. A number of people have suggested that for the dynamic case, the member access syntax should be made deliberately different to the usual dot syntax. There is a lot to be said for this.

    I was thinking that maybe to underline the fact that the method name is really no more solid than a string, you could have the syntax mimic accessing items in a dictionary.

    So instead of:

    d.LetThereBeLight();

    It would be:

    d["LetThereBeLight"]();

    It’s not a lot more typing but it properly flags up the dynamic nature of what the code is doing.

    But then I realised we can already do that today. Just make a class that has an indexer, which returns a delegate that takes a variable number of parameters:

    http://incrediblejourneysintotheknown.blogspot.com/2008/05/dynamicobject-wrapper.html

  156. Charlie,

    Would this support Dynamic Dispatch mechanism? something like:

    class MyClass

    {

    public void Something(int i){…}//(1)

    public void Something(string s){…}//(2)

    public void ADynamicMethod(object param)

    {

    dynamic{Something(param);}

    }

    }

    ADynamicMethod("hello world") would then result in call to method (2)

    ADynamicMethod(0) would result in call to (1)

    ADynamicMethod(DateTime.Now) whould result in exception.

    Is this a scenario that this mechanism will enable?

    As for syntax, I see two issues here, that have been touched upon in previous commens.

    1. please do not make it too easy to use. With that too many bad programs will be written by unexperienced developers.

    2. Make it explicit, which calls are dynamic, and which are not.

    The solution that seems the most appealing to me at the moment is going with BOTH options presented above.

    public interface Ia

    {

     public int Something();

    }

    public void ADynamicMethod(Ia parameter)

    {

    parameter.Something();//called statically just like in CLRv2.0

    parameter.SomethingElse();//compile time exception, list like in CLRv2.0

    parameter.dynamic.SomethingElse();//late bound call

    var dynamicParameter = parameter as dynamic;

    dynamicParameter.SomethingElse();//late bound call

    }

    this has two advantages:

    all dynamic calls are explicit, and we still have fine grained control over it.

    using obj.dynamic.Method(), is similar to obj.base.BaseClassMethod() we already have, so it looks more familiar than ~@!.. and other syntax suggestions mentioned earlier.

    Second option:

    var dynObj = obj as dynamic;

    I see it purely as syntactic sugar, shortcut for obj.dynamic.method

    It would NOT create another local variable but all calls

    dynObj.AMethod() would be translated at compile time to obj.dynamic.AMethod()

    that’s just my $0.02

  157. As a follow up to my previous comment.

    Adding duck typing would be also trivial and natural

    having a class like

    class MyString {int Length{get;}}

    and method

    int GetLength(string s){return s.Length;}

    We might duck-type MyString to string and pass it to GetLength method like this:

    int length = GetLength(new MyString().dynamic);

  158. Microsoft: "C# is strongly typed … Just kidding!"

  159. Tristan Labelle says:

    I choose to program in C# because I prefer statically typed languages to dynamic ones, so I’m really unsure about this new feature.

    If it was to be included in C# 4.0, I’d add my vote for the object."method"() syntax. I think that the double-dot operator could easily be confused with a single dot and dynamic blocks are a bit overkill. The object."method"() syntax makes it obvious that, like someone said, the method name is only a string (and will as such be resolved dynamically, unless it can be resolved statically). Operators might be accessed using a syntax such as object."+"(param1, param2) and generics like object."method"<Type>(param1).

    Although this is, as I see it, the best syntax for this feature, I’m still unsure about if it should be added as I fear it will be abused.

  160. Please do not implement this in C#. You have already alienated me enough with LINQ and anonymous types. (I like LINQ to SQL, I just don’t like the C# query syntax because I don’t believe it belongs in a language like C#.)

    There are reasons I switched from VB/VBA/VBScript/JavaScript to C# many years ago and this is one of them. I don’t want a language that promotes loose typing and laziness. If you really wanted to fix the problem with Office Interop, you’d make real managed classes instead of relying on tlbimp-generated code as a base. It can’t be that hard cause I have already done it for Outlook and I’m just one guy.

  161. Contrary to what many of the above commentors feel, late binding is trivial today in C# -via reflection -, and its use is inevitable in some real-world cases (people using PropertyGrid and TypeConverters frequently, can acknowledge the necessity of PropertyDescriptors etc.). I feel that an operator is in order here, rather than the block solution. As a matter of fact, although initially the thought of -> and .. operators came to my mind as I read the article, I feel that they are inadequate in the way they are proposed.

    Dynamic Lookup should NOT turn our favourite language into a hell of loosely typed constructs or a transgender language, the kinds of "I used to be the most syntactically coherent language ever devised, but now I’ll do anything for a few lines of code less". It should respect everyone’s wish for maintaining strong typing and allowing for a robust, intuitive syntax.

    IMHO, implementing an operator-based transliteration of the existing reflection tools would sufficiently cover the subject of late binding. For example, instead of

    TargetType myPropValue = (TargetType)obj.GetType().GetProperty("MyProp").GetValue(obj, null);

    TargetType myPropValue2 = (TargetType)obj.GetType().GetProperty("MyProp2").GetValue(obj, new object[] { 1 });

    (which is the way we’re used to do late binding in C# 2.0), thanks to Extension methods we can have something more coherent, like

    TargetType myPropValue = obj.GetPropertyValue<TargetType>("MyProp");

    TargetType myPropValue2 = obj.GetPropertyValue<TargetType>("MyProp2", 1);

    Obviously, obj can implement any type, and there is no specific declaration needed for retrieving dynamic properties. I personally use this a lot:

    public static class DynamicPropertyExtensions

       {

           public static T GetPropertyValue<T>(this object instance, string propertyName, params object[] index)

           {

               return (T)instance.GetType().GetProperty(propertyName).GetValue(instance, index);

           }

           public static void SetPropertyValue<T>(this object instance, string propertyName, T newValue,

               params object[] index)

           {

               instance.GetType().GetProperty(propertyName).SetValue(instance, newValue, indexer);

           }

       }

    I like this solution. It’s plain old good C#. It’ll throw exceptions if something goes wrong (we could always have a GetPropertyValueOrDefault method as well). What I would see as an improvement to the above, would be some syntactic beautification:

    TargetType myPropValue = obj.<TargetType>("MyProp");

    or

    TargetType myPropValue = obj..MyProp<TargetType>;

    and

    obj.<TargetType>("MyProp") = myPropValue;

    or

    obj..MyProp<TargetType> = myPropValue;

    The first solution allows the use of a variable instead of a property name, something that many people will certainly request sooner or later:

    string myPropName = "MyProp";

    TargetType myPropValue = obj.<TargetType>(myPropName);

    Obviously, the generic parameter can be inferred from use in some cases.

  162. Lexapro 20mg. Lexapro. Lexapro and side effects.

  163. 刘望 says:

    That’s great,I am glad to heard that.

    I am sure the next version of Visual Studio will be perfect.

  164. 刘望 says:

    That’s great,I am glad to heard that.

    I am sure the next version of Visual Studio will be perfect.

  165. Mike says:

    Just to add another idea: couldn’t this perhaps be done partly at the library level instead of adding another keyword to the language, something along the lines of Nullable<T>?

    I mean something like:

    Dynamic d = new Dynamic(GetDynamicObject());

    d.SomeMethod();

    where the compiler translates d.SomeMethod() to something like d.Call("SomeMethod").

  166. I’ve not watched many Channel 9 videos over the last few months, but every now and then some really good

  167. The syntax outlined can become very clunky and dangerous because usually such block of code will contain mix of late binding as well as early binding (assuming not all programmers are perfect). I would suggest you invent a different calling notation other than "." to make dynamic call. For example, may be we can define ".." as replacement for "." for dynamic calls. So whenever ".." follows identifier it would specify that next operator/method should be invoked dynamically.

    object myDynamicObject = GetDynamicObject();

    myDynamicObject..SomeMethod();        

    myDynamicObject..someString = "value";

    myDynamicObject..[0] = 25;

  168. Anthony D. Green says:

    I don’t normally make these kinds of posts but I’m taken aback by this.

    We had this feature for years in VB. We called it Option Strict Off. We could set it at the Project level, the File level, and through use of partial classes even at the method level. And for years we caught nothing but grief from the development community over it.

    And now that you want to "shoehorn" it into C# it’s a "cool new feature" that all the jocks and cheerleaders use while drinking Pepsi. I don’t get it. This reversal of prejudices lobbed at VB for generations all because it’s applied to the trendy languages confuses and insults me. This was a horrible, not-best-practice, bad-coding-practice feature 10 years ago and the C# community should have to live with and accept this as a vile black mark on its perfect language for all time like I’ve had to (no matter how useful it is). You can’t make this "good" now that you want it.

    First Edit & Continue and now this. Can’t the C# universe stick to its elitism and stop ripping off VB.NET? Nevermind that it encroaches on the VB market niche. The end result of this language bloat will be the same fate that befell VB and C++ before it:

    A monstrous all inclusive language anchored to legacy code with a subcontinent of diverse development groups that make it impossible to identify a target audience.

  169. One of the common feature requests for IronPython is to support static compilation. While the feature

  170. aL says:

    i agree with the people promoting the

    dynamic object foo

    approach infavor of a block..

    a block seems clunky to me..

    however i dont agree that there should be some special operator to call dynamic methods. the ide knows the type of the untyped object so to speak so it can highlight the member calls as dynamic..

    i also agree withthe people saying that this should be implemented with extreme care..c# is at its core a static language and there are many many many great things with that.. please dont loose those advantages just to please the dynamic crowd..

    that said, expanding the language is great! just dont loose the great things that are already in there.. 🙂

  171. aL says:

    i agree with the people promoting the

    dynamic object foo

    approach infavor of a block..

    a block seems clunky to me..

    however i dont agree that there should be some special operator to call dynamic methods. the ide knows the type of the untyped object so to speak so it can highlight the member calls as dynamic..

    i also agree withthe people saying that this should be implemented with extreme care..c# is at its core a static language and there are many many many great things with that.. please dont loose those advantages just to please the dynamic crowd..

    that said, expanding the language is great! just dont loose the great things that are already in there.. 🙂

  172. Paul Wheeler says:

    I want to cast my vote for the ! calling syntax instead of blocks:

    myObject!Method();

    myObject!"Method"();

    myObject!Property = 0;

    myObject!"Property" = 0;

    It fits nicely with anyone who used vb6 back in the day!

  173. Sameer says:

    At the risk of sounding like a dork this is kind similar to Powerbuilder( at least from what I remeber of it).  Guess the language was ahead of it’s time.

  174. I agree with the comments made by Thomas Krause, Daniel Earwicker, and Simon Watfa: dynamic object MyOfficeObject (for syntax, instead of the dynamic code block), I dislike the idea of a separate member-access operator (C++ is a mess of operators), and that C# should only be a consumer of dynamic objects (and remain static).

    Charlie, you said declaring a whole object as dynamic is too broad.  What you mean by that?  What specific scenarios have you come up with that demonstrate this problem?  If you always first try to do static lookups, and only perform dynamic lookups when that fails (and only on variables marked as dynamic), what problem remains?

    C# should remain static, but by using extension methods, it can take on the appearance of being somewhat dynamic, in the sense that we’re "adding" members to types, at least for code that references the appropriate library and imports the right namespace.  It’s not flexible to the point of being able to add and remove members at runtime, but I can’t think of a situation that more would ever provide significantly more value (which isn’t to say there is none).  My only request here is that C# incorporate general type extensions instead of limiting them to extension methods.

    Some kind of duck typing or structural typing would be very useful, and wouldn’t require dynamic typing in the language, but as others have stated, this doesn’t address the needs of accessing types whose members change during runtime.

    While I don’t want to be able to modify classes during runtime by adding or removing members, it would be VERY useful (for aspect oriented programming) to allow dynamic dispatch for pervasive method interception.  Keep the interface of a class the same, but allow calls to be rerouted to different bits of logic.  .NET has a TypeForwardedTo attribute, but this would be a more powerful, fine-grained (member-level) approach.  Perhaps extending the language, or providing new reflection-like classes for intercepting individual members (properties and methods), all members of a type, etc.

  175. Aaron M says:

    It should definitly try to resolve statically first, because we want to have code completion available inside dynamic blocks when it is available and just have nothing when its not… 🙂

  176. Aaron M says:

    I would like to see generics inheritence compabitility… eg….

       class Fruit

       {

       }

       class Apple : Fruit

       {

       }

       class Orange : Fruit

       {

       }

       // THis wont compile because we cant

       // define a base class for the

       // generic type, but i want it to work

       class FruitPackage<Fruit fruitType>

       {

       }

    Now we should be able to create:

    FruitPackage<Apple> oApple = new FruitPacakge<Apple>();

    and

    FruitPackage<Orange> oOrange = new FruitPacakge<Orange>();

    Then i want to be able to go

    FruitPacakge<Fruit> oFruit = oApple;

    or

    FruitPacakge<Fruit> oFruit = oOrange;

    We should be able to define a base type for generics, this could make generics much more useful… it would be good if this worked in VB.NET as well as C#.

  177. Aaron M says:

    Previous comment:

    class FruitPackage<Fruit fruitType>

    Should probably be more like:

    class FruitPackage<typeof(Fruit) fruitType>

  178. Aaron M says:

    Back to the issue at hand, i like the dynamic block idea, it makes it clear where the dynamic calling can occurr, which means its easy to spot, and easy to perform QA on to ensure its not being overused. The only problem i see is allowing a mix of dynamic and static calls, as far as im concerned if any calls can be statically linked and are in a dynamic block the compiler should fail.

    Sure this might mean a little more work because you may have to have more dynamic blocks than you would previous need, but this will stop overuse and keep C# to a static language as we all like it….

  179. Hi,

     how about adding dynamic interfaces to the language?  Interfaces are perfect for static typesafe dynamic coding and fit into the tool feature set quite well too.  What do i mean?

    Given an object _obj_ that may or may not be dynamic, anonymous, concrete whatever.  I can declare a variable _x_ such that x exposes a public method/property/field through a dynamic interface.  for instance var x:{void Walk();}. With this type of feature, one can cast anything to anything as long as theor interfaces <dynamic or otherwise> match.

    At assignment time (ie- _x_ = _obj_ 😉  the runtime or vs.net can check to ensure that _obj_ exposes the interface as well.  Its seems like an easy way to give us a TON of functionality; including finally able to interact with anonymous types outside of a method without having to have a known type to copy it into.

  180. A post by Jeremy Miller caught my eye this morning in regards to extension methods in Javascript . While

  181. anon says:

    How about using # for dynamic member access?

       Foo#Bar()

    It stands out a lot more than .. or ! in my opinion.

  182. Victor Rodrigues says:

    Would be interesting if I could do something like that:

       dynamic

       {

          object dynamicObject = GetDynamicObject();

          string method = "Foo"; /* or a call to somewhere in order to initialize this string */

          dynamicObject.method(); /* in this case, it means ‘dynamicObject.Foo();’ */

       }

    The goal of DLR is to ease the way we use reflection in C#. Since this construct can’t compile in normal C# (object.stringIdentifier() ?), a dynamic block allowing this would improve reflection usability.

    I know that according to the definition I saw on this post this should call a method named ‘method’. But when there is an identifier on the block with this name, could be more interesting to the developer to use this information. This identifier could refer basically to a string, but pottentially to other objects with more method info.

  183. Victor Rodrigues says:

    And about the syntax, I think ‘..’ is the best option, allowing of course the dynamic block also.

  184. PDC 2008 arrives today, and that means that I am finally able to talk publicly about some of the things

  185. Muitas novidades aconteceram e vem acontecendo no mundo de tecnologia e desenvolvimento. Principalmente

  186. C# 4.0 Dynamic Lookup I really like the way the C# team tackled bring dynamic programming to the language

  187. I don’t care what the syntax is AS LONG AS I CAN MAKE IT AN ERROR TO USE IT in the project settings.

    Ideally it would like unsafe where you have to go turn it on.

    The top 2 horrible things about VB.NET are:

    1) The background compiler

    2) Late-binding

    For the love god, please do not trash C#.

  188. Many .NET users have no doubt run into issues using math functions with generics. Let’s say you want

  189. Lawrence says:

    IronPython in action, embedding dell’IronPython engine

  190. Lors des techdays 2009, je suis allé voir la session “ Programmation dynamique ” de Mitsu Furuta et Simon

  191. An attentive reader pointed me at this long thread on a third-party forum where some people are musing

  192. 出会い says:

    ヒマだょ…誰かかまってぉ…会って遊んだりできる人募集!とりあえずメール下さい☆ uau-love@docomo.ne.jp

  193. 小向美奈子 says:

    話題の小向美奈子ストリップを隠し撮り!入念なボディチェックをすり抜けて超小型カメラで撮影した神動画がアップ中!期間限定配信の衝撃的映像を見逃すな

  194. 話題の小向美奈子ストリップを隠し撮り!入念なボディチェックをすり抜けて超小型カメラで撮影した神動画がアップ中!期間限定配信の衝撃的映像を見逃すな

  195. カワイイ子ほど家出してみたくなるようです。家出掲示板でそのような子と出会ってみませんか?彼女たちは夕食をおごってあげるだけでお礼にHなご奉仕をしてくれちゃったりします

  196. 右脳左脳 says:

    あなたは右脳派?もしくは左脳派?隠されたあなたの性格分析が3分で出来ちゃう診断サイトの決定版!合コンや話のネタにも使える右脳左脳チェッカーを試してみよう

  197. セレブラブでは性欲のある男性を募集しています。セフレパートナーを探している20代・30代の女性たちが多数登録されています。セレブと遊びたい、Hがしたいという方は無料登録からどうぞ

  198. 逆援助 says:

    セレブ達は一般の人達とは接する機会もなく、その出会う唯一の場所が「逆援助倶楽部」です。 男性はお金、女性はSEXを要求する場合が多いようです。これは女性に圧倒的な財力があるから成り立つことの出来る関係ではないでしょうか?

  199. 救援部 says:

    貴方のオ○ニーライフのお手伝い、救援部でHな見せたがり女性からエロ写メ、ムービーをゲットしよう!近所の女の子なら実際に合ってHな事ができちゃうかも!?夏に向けて開放的になっている女の子と遊んじゃおう

  200. 出会い says:

    まったぁ〜りしたデートがしたいです☆結構いつでもヒマしてます♪ m-g-j@docomo.ne.jp 年齢と名前くらいは入れてくれるとメール返信しやすいかも…

Skip to main content