I’ve been reading about how the C# team is considering putting the option to call dynamic code within C# directly and I have been looking at some of the syntax they have been proposing publicly. It also seems like there are a handful of people who are proposing their own ideas of how to express various features of C# they wish existed so I thought I’d propose one of my own.
Personally I find the idea of a dynamic method or a dynamic block a little clunky. So I would like to propose a different possible solution.
The whole idea is that in C# the compiler has to know the type of a variable so it can guarantee that the method you are trying to call exists. This is largely the purpose of interfaces. However, there are some circumstances where you might prefer to call a method dynamically. The dynamic method block syntax Charlier Calvert is proposing is very reminiscent of the “unsafe” synatx in C# however if you really wanted to make the language more dynamic in general I think you could simply have the option to call the memeber with something other than a ‘.’ to indicate that it should be a dynamic call. Something more like:
string example = obj:Example();
In this case I’m suggesting that merely replacing the ‘.’ with a ‘:’ will cause the application to call the Example method dynamically. I belive this would still conform to the explicit nature of C# while making dynamic calls quite flexible. If the colon was an undesierable character it would be simple enough to just use something else.
In this case you would not get much intellisense related to the parameters or return value of Example wich I believe would prevent it from being used except in circumstances where it was absolutely needed. Also you would only get runtime exceptions if the types of the parameters and return values were incorrect. It would probably have to assume that the return Type was actually an object if you used the “var” syntax.
Also, you would need some way to check to see if the member existed at the very least:
string example; if(exists(obj:Example)) example = obj:Example();
Of course, this should be essentially the same for fields, properties and events. For example:
string example = obj:Example; // field or property obj:ExampleEvent += new EventHandler(OnExampleEvent);