Search Wiki:
Resource Page Description
Samples and documents describing C# 4.0 language and IDE features.


Visual Studio 2010 Beta2 and Beta 1 Samples are now live!


Samples and documents for C# 4.0 can be found on the Downloads page. The CSharpDynamic samples include several projects showing how to use Dynamic with Office, IronPython and other technologies. There is also a covariance and contravariance example, and an example show how to use the new IDynamicObject interface to create native C# objects that can be called dynamically.

The document New Features in C# 4.0 is a high level description of the additions to the C# language, and the samples are designed to show off the new language features, particularly around the dynamic scenario.

Please see the walkthroughs that ship with Visual Studio 2010 Beta1 for additional information about these samples. The code in these samples is preliminary, and may not run correctly. We recommend installing the samples on the root drive of your system, for instance, place them in c:\beta1_samples. These samples may be modified by the C# team at any time, so you might want to check back occasionally for updates.

Please submit bugs through connect, or provide comments in the discussion section of this site.

It is important to remember that the code shown here is preliminary, and is designed to run on a beta version of Visual Studio 10.0. This code may not work correctly, and the syntax shown in this code may change before VS 2010 is released.

The Office example ought to run smoothly if you have a copy of the most recent version of Microsoft Office installed. It may also work with older verisions of Office. The Python example will work if you download IronPython 2.0 . It may also work with more recent versions of IronPython. You will need to replace the IronPython, IronPython.Modules and the Microsoft.Scripting assemblies found in the references section. Right click on the References node in the Solution Explorer and choose Add Reference. Browse to the directory where you installed IronPython and add the missing Assemblies. By default, IronPython is installed in the Program Files directory. Please come back here later for additional information about the Silverlight example.

Thank you for your interest in Microsoft products.
Last edited Oct 19 2009 at 10:37 PM  by CharlieCalvert, version 21
Comments
Danfma wrote  Oct 28 2008 at 2:13 PM  
One thing that I think that could be a great feature in C# 4, if included, it is the contracts of the Spec# nativelly on the language, this will help to make softwares with less errors and with all the power of the C# 3.5+ that we all know...

PeterMorris wrote  Oct 28 2008 at 5:14 PM  
Personally I would love to see pre-compile support for AOP
http://mrpmorris.blogspot.com/2008/10/how-i-would-like-to-write-code.html

I would really like to be able to do this

[ImplementINotifyPropertyChanged]
public class Person
{
public string Name { get; set; }
}

var npc = (INotifyPropertyChanged)new Person();

It's a simple example, but being able to simply identify features an assembly, class, or member has using attributes would be great. I can do this now with PostSharp, but having pre-compile support for this would be like a dream come true!!!

justncase80 wrote  Oct 29 2008 at 5:21 AM  
Yes, I agree with Peter. You can do this in boo quite easily, I would love to see the meta programming features of Boo in C#! 5.0 perhaps???

levasseur wrote  Oct 30 2008 at 4:24 PM  
What I would like is something like "typedef" in C++. I know this idea is debateable. Like many other language issues, there are pros and cons. Instead of code like this:
public Dictionary<int, List<Person>> GetPersonsInOffice()
{
Dictionary<int, List<Person>> myColl = new Dictionary<int, List<Person>>();
...
return myColl;
}

With typedefs, you could have...
typedef List<Person> PersonColl;
typedef Dictionary<int, PersonColl> OfficePersonsColl;
..
public OfficePersonsColl GetPersonsInOffice()
{
OfficePersonsColl myColl = new OfficePersonsColl();
...
return myColl;
}

I think the latter is more readable. On top of that, if you ever want SortedDictionary instead of a Dictionary, you just change your typedef to

typedef sortedDictionary<int, PersonColl> OfficePersonsColl;

and you wouldn't need to change all your types everywhere (although you might need to change a bit of logic). When you have a language with types like "dynamic", why not also have "typedef"? Typedef is so handy that C# even uses a form of implicit typedef with it's basic types (for example: the "int" type a System.Int32 ?).

rweads0520 wrote  Oct 30 2008 at 10:34 PM  
I was a little surprised by the syntax for named arguments, i.e. a.Foo(i: 10, s: "Bob"). The syntax already used for specifying named members in attribute declarations and anonymous types, the equal sign, i.e. a.Foo(x = 10, s = "Bob"), seemed more expected and natural to me. Great and long-overdue feature, though.

SneakerXZ wrote  Oct 31 2008 at 12:26 AM  
levasseur: Don't get me wrong, but C# got using keyword which you can use as alias, but I am not sure if it works with generic.

http://msdn.microsoft.com/en-us/library/sf0df423(VS.80).aspx

TomServo wrote  Oct 31 2008 at 2:41 AM  
I also really like Peter Morris' AOP suggestion. I am sure there are many uses for that construct. I also like the typedef idea (of course I started out with K&R C many years ago).

@SneakersXZ
The "using" trick almost works, but not quite. For instance,

using MyPeople = System.Collections.Generic.List<Person>;
using MyColl = System.Collections.Generic.Dictionary<int, MyPeople>;

This won't compile unless MyPeople is outside the namespace and MyColl is inside. And the intellisense for MyColl shows List<Person> instead of MyPeople as the second type. Nonetheless, it's close and an interesting idea.

With this in mind however, it might be an easy change to make using declarations immediately available to following using declarations. Having intellisense show List<Person> as MyPeople is another questions, but would also be nice.

abjbhat wrote  Oct 31 2008 at 8:37 PM  
I second the request for typedef. I use it a lot in C++, its useful...and I'm sure the C# team could come up an "improved" version. Think delegates.

MillKa wrote  Nov 1 2008 at 5:02 PM  
typedef++ (that means i am missing typedef too)

ScottJones wrote  Nov 1 2008 at 5:57 PM  
typedef++ for me too. Like SneakersXZ, found usings technique for 'poor-mans' typedef, along with its limitations.

Also, would like more liberal delegate comparisons. E.g. Predicate == Func<bool>. Does the new variance support offer that?

akx wrote  Nov 3 2008 at 3:55 AM  
Named arguments - I assume you have a very good reason to use : instead of = in method invocation, however the latter is more consistent with the rest of the language IMO. -1 for typedef as it adds to code obscurity and sometimes is blatantly abused, the above example - public Dictionary<int, List<Person>> - can be implemented with .NET type Lookup<int, Person>. I'd like to see many F# features incorporated into C# 4.0, which means more functional programming tools. I'd like you to work something out to eliminate some obvious constructor calls like MyTypeName variable = new MyTypeName(), and similar syntax constructs, if possible. I'd like to see 2 more extension methods for IEnumerable<T> (yes I know it's BCL but here's the opportunity to share the whole wishlist ;-) - ForEach and IsNullOrEmpty. More data structures -- a decent implementation of different tree-like data structures, which are missing from BCL altogether, for example red-black tree, binary search tree, AVL tree or anything (you decide ;-) Thanks!

ibrahimlibyan wrote  Nov 17 2008 at 9:05 PM  
hi
book help us
in arbic

Dingo wrote  Nov 19 2008 at 8:51 AM  
Any chance to have non-nullable reference types. I.e.
Order! order = new Order( ... ); // order is known to be !=null
ProcessOrder( order ); // ProcessOrder will never have to deal with null orders

TanSilliksaar wrote  Nov 20 2008 at 9:38 AM  
I absolutely love it!
Currently, overload cannot resolve by return value. Will that change in v4?
This fails but it could figure out what I intend to do if it had more intelligence:
string Get(object o)
{
return "x";
}

int Get(string s)
{
return 1;
}

void Do()
{
string s = Get("s");
}

skhar wrote  Dec 10 2008 at 11:42 AM  
2 TanSilliksaar:
Actually as I know CLR supports overriding by only return value. But this is prohibited in C# because of misleading calls of Methods.
How can you recognize what method should be called if I code:
string Get()
{
return "x";
}

int Get()
{
return 1;
}

object someObject = Get();

I'm highly doubted that this feature will be available if it was not supported in C# since 1.1 version.

But new Feature with generics ++ (zachot!)

Dunross wrote  Dec 10 2008 at 8:59 PM  
I really don't like the new "dynamic" features in C# 4.

I was using PHP langugage for about 5 years (and no, I wasn't writing procedural code, but instead I was using the most advanced frameworks of that platform) and after this experience I've gained a strong opinion that dynamic languages are not suitable for any big project. And that is why I turned to C#. It is precompiled, easily debuggable and maintainable.

And now it may be lost. I fear that many new developers will be excited by the new dynamic features and that they will start to use it widely. That wouldn't be good, I think.

Raine wrote  Dec 21 2008 at 12:14 PM  
Hello, I second what akx said; the : in the method invokation doesn't seem to be coherent with the rest of the language, and it reeks of Pascal. While I like all the new features, this little change seems to be turning the language into a dashboard for all kind of new features.

trialtrial2007 wrote  Dec 22 2008 at 7:39 PM  
Like PeterMorris, I would like to do something like this. I can apply an interface for the objects (whose class has been containing the signatures defined in the interface) at the stage of coding/runtime by modifying that object class 's attributes. By this way, I don't need to call functions of the objects via reflection. Depending on the way of the attribute implemented, the class codes of objects will be optimized. Is this not good?

meissnersd wrote  Dec 29 2008 at 10:45 PM  
Yes! Lets kill null reference exceptions with static compiler checking.

I want to be able to specify that an object reference is never null. C++ has similar feature with the & as an safer alternative to pointers. It much easier to be confident you never get a deference exception on signatures of the form

class A
{ public:
F& getF();
);
so this is safe from nulls
A a;
a.getF().DoSomething();

Once an reference is not null, I would like the compiler to statically check that every assignment is either for a NeverNullReference or is explicitly checked on assignment. Attempts to assign a null from a normal refernce would throw.

This would be a nice complement to nullable primitive types.




JerryKabaka wrote  Jan 20 2009 at 4:59 PM  
The dynamic language element is a waste of time. This is dynamic relying on statical structure. The developer must know before hand what operations, variables, properties a dynamic type support. So why the dynamic since it depends on a known static definitions.

This is reflection in disguise. Its of no use if it cannot support something like the following :

Again why can we make the object as the dynamic it self as in :

object d = new Foo();
d.M(22);
d.Go(55);

Since the dynamic complement the object why not use object. How many language elements do you guys want developers to know to use C#. C# should be more simple and focus on adding more class libraries.

keremskusmezer wrote  Jan 30 2009 at 7:18 PM  
I got the following questions on the topic dynamic:
Will there be a pragma switch or something like option strict on in vb to disable dynamic usage in the project.
Because i don't want to see code like this in my project:
dynamic tstring = "test";
tstring.IndexOf("test");

WillHuang wrote  Feb 8 2009 at 3:39 PM  
There is a typo in "New Features in C# 4.0" documentation.
Page. 9: Variance section: These is a sample code:
string s = strings[0];
should change to
string s = objects[0];

Maral wrote  Feb 17 2009 at 7:30 AM  
You need a simple way to encrypt an existing file on the file system so that only the account used to encrypt the file can decrypt it.

mastermemorex wrote  Mar 17 2009 at 11:09 PM  
Yeah! Typedef and non-nullable types for me too. About dynamic types will be prone to bugs and run-time exceptions and as far as performance is anyone's concern it should be as far away as possible from anyone's code. Instead I would rather prefer more flexible constrains, mixing data types, more controlability of the GC and memory levels. Any new feature that do not strongly support high performance computing and real-time applications is a waste of time.

trialtrial2007 wrote  Mar 22 2009 at 4:09 PM  
I would like to trace all of local variable values of the methods specified by certain attributes in Release Mode as well as in Debug Mode. If these local variables have already been traced, I can use PostSharp automatically to serialize them which are the local variables, method arguments, stack traces, etc at the stage of the exception thrown. By the way, at any time can I serialize them too. The serialized objects will be used to reproduce the exception. If this trace method is supported, I think it is very useful to make the exception process simplier for developers because they don't need to write each trace for each local variable.

SeanPalmer wrote  Mar 29 2009 at 3:20 PM  
I also would like to see some kind of typedef added. If not, at very least allow using clauses inside classes and structs (and functions!) instead of just at the top of a source file and in namespaces. I truly don't see the harm in that.

The main thing I'd like to see though, is some kind of interface added to the basic system numeric types that allows one to constrain generics to provide a set of operators. Currently it is very unwieldy to write generic functions or types that make use of operators. I won't be happy until I can write at least a simple lerp<T> function:

T lerp<T>(T a, T b, float i) where T : IAdd, IMul { return a * (1-i) + b * i; }

Right now that simple function is ridiculously difficult to implement in C#. All the basic system types (int, float) should provide the appropriate numeric operator interfaces. There are plenty of ways to implement this, and honestly I don't care how you do it--it's a feature I sorely miss from C++ (along with typedef!)

Oh, and please fix System.Drawing Point and Size types so you can add, subtract, and scale by float! They're not very usable as is. We need some real numerics in CLR: good vector, complex, and matrix classes.

NTDeveloper wrote  Apr 13 2009 at 1:41 PM  
I know I'm whistling in the wind here, but I would really like to see MULTIPLE CLASS INHERITANCE. And, yes, I know that certain aspects of MI can be simulated by interfaces and containment/delegation. What I am asking for is real multiple inheritance such as that found in C++. The authors of ATL at Micrsoft certainly realized the benefits of MI. Why can't we have this feature in C# and other managed langages? I understand that supporting this feature would introduce certain complexities into the runtime and that it does give users another chance to shoot themselves in the foot, but there are certain scenarious that just beg for this construct.

RazvanM wrote  Apr 16 2009 at 4:03 PM  
I really don't see the point of dynamic, i mean if you know the name of the method / field etc then what's the point of interfaces, what could be done is define an interface say
IGetSomething
{
int get();
}

and let the runtime map the interface to the object does not matter where it comes from, just map the interface to the object

IGetSomething g = GetDynamicObject()......

lorenzo wrote  Apr 26 2009 at 2:10 PM  
typedef++! Absolutely great for nested types... (where "using" don't work)

marquinhocb wrote  Apr 26 2009 at 3:13 PM  
rweads0520, akx:
The reason for using : instead of = is simple, and that is that the equal sign already means something. If you have
int myInt;
CallSomeFunction(myInt = 5) <-- That could mean that we want to set myInt to 5
CallSomeFunction(myInt : 5) <-- That means we want to set the myInt parameter to 5.

I understand why the DLR has been developed, to support dynamic languages in the CLR. But I don't see why this should mean that much-needed static constructs should be left behind.
For example, CS0404: attributes cannot be generic - this is something that desperately needs to be fixed in C#.
Also, some other additions to make C# more static-friendly. For example, it's currently not possible to get a PropertyInfo or MethodInfo statically. It would be really nice to have typeof(SomeClass.SomeProperty) and typeof(SomeClass.SomeMethod) return a PropertyInfo and MethodInfo respectively.

Other than that, great job, keep it up!

marquinhocb wrote  Apr 26 2009 at 3:20 PM  
typedef++ here too, it's something incredibly simple to add to the language that won't dirty it up.
NTDeveloper: I won't argue with you, that multiple class inheritance has its advantages. But there's a reason it's a big "no-no". Not sure if you've ever taken a compiler class? Implementing multiple class inheritance is an absolute nightmare. The overhead and ugliness that multiple class inheritance adds to a compiler makes it simply not worth it.
It would be interesting, though, to add something like the "this" parameter to a class member. What I mean is:

public class SomeOtherClass
{
public void DoSomethingCool();
}

public class SomeClass : BaseClass
{
public this SomeOtherClass OtherClass;
}
SomeClass myVar = new SomeClass();
myVar.DoSomethingCool(); (I call it without having to specify myVar.OtherClass.DoSomethingCool())

The cool thing about the above is that it would allow you to use another class for functionality (which is really the only point of multiple inheritance), but it wouldn't bring on the nightmares of multiple inheritance.

mastermemorex wrote  Apr 27 2009 at 10:16 PM  
I don't like the : notation for one simply reason and is because optional parameters has already exist in C++ and we have always used foo(int index = 0). Why C# should use something different? It will create some unconfort fealings for a lot of programmers.

marquinhocb : I use multiple inheritance to mix data types and I find it very useful. Let's say for example that you are working with DirectX and you have one vertex format with position and texture and another vertex format with position and color and you want to combine into a vertex format with position texture and color. There is no way to do this in appropiated way without multiple inheritance or re-writing all your code for every vertex format.

chandra2ravi wrote  May 6 2009 at 8:23 AM  
when it is release date.

roseen wrote  May 7 2009 at 1:46 PM  
mastermemorex: You are confusing optional parameter (that *does* exist in C++) with named parameters (that does not).

When it comes to optional parameters, the syntax is the same in C# as in C++.


roseen wrote  May 7 2009 at 1:54 PM  
Talking about dynamic; just because it is needed in the CLR (or in the DLR, really), there's no reason to include it in C#.
There are many features in the CLR that is not available in C#, and we are still OK... :-)

So, I challenge you: is there anyone here who can show us a situation when dynamic will actually be beneficial (in C#)?

I've seen some examples where you instantiate a type an call a method on it, and you save one (1) line in a five line example by using dynamic. Woooow... No, I just anticipate a lot of sloppy programmers using this to write sloppy code that will be a nightmare to maintain.

After all, when we are talking "enterprise" code, the time/cost of writing the initial code is minimal compared to the time it takes to verify, test, debug, document and maintain... If the coder can save a few keystrokes by writing code that will be harder to maintain, the net result is definitely negative...

KeithBlue wrote  May 7 2009 at 5:47 PM  
I strongly support the prior discussion of adding 'typedef' support to C#. This is something that I also sorely miss as a former C++ developer. To implement this in C# in an enterprise setting (i.e. many groups & teams using common code), we have had to create strong wrappers for a bunch of classes, each of which must include conversion operators, hash codes & equality methods, and other basic stuff. For instance (in the advertising space) we have routines that accept "clicks" (as in a click on an ad), which is basically just a Uint32. But to ensure that developers pass a "Clicks" entity and not just an integer, we need to create a wrapper class, each of which takes ~100 lines of code. It seems like it would be pretty straightforward to do. (BTW, the "using" syntax is reasonable but is also manual -- every source file has to have the same usings added manually across the enterprise to achieve the same effect.)

Lastly, some more help to be able to automatically reclaim resources would be great. Under C++, the destructor was a great place for that, allowing true encapsulation & management of resource lifetime. I understand (and appreciate) the benefits of garbage collection, as well as the improvements to object creation performance. IDisposable is the interface indicating that a class should be Dispose'd of as soon as possible; yet it requires manual coding (the using statement) in each place it's created. Why not at least enable the developer to give the CLR (or compiler?) a hint that the runtime should check for 'disposability' (i.e. class is GC collectable) when the declaring scope is exited? Typically, developers will acquire/create a disposable resource (connection, proxy, etc), use it, then dispose of it -- they're not typically held for a long time. While this might not be perfect, it's a step in the right direction. As an example, a single developer failing to dispose of a connection-oriented WCF proxy can cause the target service to be unavailable. It would be worth the runtime hit to be able to say (declaratively) "when this resource exits the declaring scope, see if we can dispose of it, and if so, do it."

roseen wrote  May 7 2009 at 7:00 PM  
Ahh! This is one that I would vote for!

"Automatic using"... It is quite simple the way it is today, but you need to to it in every place, and when multiple IDisposables are used in the same segment of code, the syntax quickly becomes cluttered.

I would vote for some kind of attribute, or perhaps as a different way of calling "new", that signals that Dispose should take place on leaving scope.

Ibasa wrote  May 26 2009 at 11:14 PM  
Couldn't the compiler check the source to see if there's any way that the object could persist out of the method, and then if there's no way that it could be accessed again at the end of the method the compiler automaticly adds a call to Dispose().
Could go even further and objects that cannot persist beyond the method could be stack allocated, even if its a class, thats probably not needed though.

eroosendaal wrote  Jul 15 2009 at 1:24 PM  
I would like a very simple enhancement. Currently VB, Java, C# and others have different ideas on the default scopes of variables, methods and classes. That's confusing. Why not make the use of an explicit scope (public, private, internal or protected) mandatory? A project converter could easily supply the defaults when upgrading, and backward compatibility would be no problem.

The_Assimilator wrote  Jul 17 2009 at 3:32 PM  
A situation where "Dynamic" would be hugely beneficial in C#:

http://tore.vestues.no/2009/01/05/creating-a-dynamic-xml-reader-with-c-40/

Same concept applies for typed datasets.

As for features in C# 4.0, I like the typedef idea. But what I'd also like to see is the preprocessor being enhanced to support C/C++ #define syntax, i.e. macros:

#define SQUARE(x) ((x) * (x))

For example, if you have a list of strings pulled out of a database that you want to transform into variable names, there's no way to achieve this in C#. But with #define you can (although it would make debugging trickier).

kainhart wrote  Aug 21 2009 at 2:51 AM  
AOP, especially some way to hook into property getters and setters

A keyword (perhaps owner) for self referencing the current type
https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=470524

As far as the (parameter1: value, parameter2: value) syntax goes, double yuck!! I was totally expecting (parameter1 = value, ...) since that is what is used in initializes as well as anonymous types and unfortunately this looks more like inheritance :(

Language support for Design by Contract concepts such as in spec#. I'm thinking that the non-null reference type suggestion by meissnersd could be implemented using DBC too.

A base interface or set of interfaces for numeric types (although this is more of a .NET Framework request)

oh yeah and typedef++ for me too

I agree as well too that the dynamic keyword is likely to become problematic and I would probably rather seen other more important features listed above implemented before this, but I do see the benefit in terms of Linq to SQL, XML, reflection, and COM programming although if no tricks are done to provide intelligence then I think this feature is even more closer to useless and even dangerous since it makes reflection like programming look like regular programming so that it is hard to spot and call out shenanigans.

rjfhendriks wrote  Aug 27 2009 at 10:53 PM  
MI could be an option. Just check if there are no overlapping methods, fields etc. It's just needed sometimes to prevent double code or use ugly static helpers. F.e. I have an EditForm and ListForm and a SecuredForm and want to have a clean EditSecuredForm and ListSecuredForm: just impossible without using tricks. DLR is coming: maybe add a templating kind of include feature, maybe not a very clean option but code is in one place....

bklooste wrote  Sep 25 2009 at 4:39 AM  
Sad their are no non nullable reference types..

yurash wrote  Oct 8 2009 at 4:24 PM  
And what about const local variables?
I think they should be extended like in C++ so their values could be calculated at run time. Or maybe "readonly" modifyer for local variables would be more appropriate for this.
It could be very useful in declarative-style programming.

yurash wrote  Oct 8 2009 at 4:35 PM  
And of cause "typedef" is much better than "using". "using" is like #define, it is somehow out-of-language. Whereas "typedef" in C++ is true object-oriented feature.
Real substitution for "typedef" is not "using", but derivation. But the latter is an overhead.

TimothyBussmann wrote  Oct 11 2009 at 2:36 AM  
I'd really like to see the restrictions on generic where constraints relaxed to allow specifying Enum (And Delegate, and possibly Array). This would also be nice, though probably harder to implement, but allowing generic constraints on operators like + - / * || && etc..., these would be currently most similar to the new() constraint in that they are a structural type constraints.

Along with that, support for strong structural typing (anonymous typing is a most basic example since type matching is based on the structure of the type, not its name) -- allowing pattern matching similar to Scala.

Finally, and this is one wish I think I will be granted with the next version of C# is stronger metaprogramming facilities. Continue down the direction of code as data.

Tim

yurash wrote  Oct 12 2009 at 4:52 PM  
Oh, yeah! "generic constraints on operators like + - / * || && etc...", or maybe better would be generic operators in interfaces.
Generally, operators should be like all other methods (aren't they, really?). Why operator+(.) should be different from operatorPlus(.) method? I'd like to write something like this:
interface IAddable<T>
{
T operator+(T a, T b);
}

Arithmetic types should implement these interfaces, too. But oops! - we can not write "struct int : IAddable<int>" - it is not C++ template... There is a problem here... :(

As to generic constraints, constructor-with-given-arguments-list constraint is needed, too (not only simple "new()").

yurash wrote  Oct 13 2009 at 1:19 PM  
Another question is an optimization. Why does the compiler no optimization in release version? I've found in the Reflector that even constants have not been summed up in the code like this:
int n = 10;
int m = n + 6 + 7 + 8; // it is the same in the Reflector!!!
Only the following has an effect:
int m = n + (6 + 7+ 8); // it is "n + 21" in the Reflector

z5ivan wrote  Nov 4 2009 at 10:25 AM  
Make { } assigning more generel. Today it only works on constructors, make it work on any function call.
new Foo{ Name = "test" } // constructor assigning is possible today

It should also be possible to assign members after af function call, like this:
Factory.CreateFoo(){ Name = "test" } //should be possible in the future

MarkSmeltzer wrote  Nov 9 2009 at 6:16 AM  
I was really hoping to be able to use dynamics to work around the "no generic base classes" restriction in .NET, to allow creating dynamic interface redirection as follows:

public class InterfaceRedirector<T> : DynamicObject
{
public override bool TryInvokeMember ( ... )
{
....
}
}

dynamic redirector = new InterfaceRedirector<ISomeInterface>( );
var item = (ISomeInterface) new SomeItem( );
var receiver = new InterfaceReceiver<ISomeInterface>( item, redirector );

var contract = (ISomeInterface) redirector; //the application will crash at runtime here!

contract.SomeMethod("hello world");

----------------

It would be really great if we could use dynamics in the way specified here and just suppress the runtime type checks. This could perhaps be accomplished by adding another virtual method to the DynamicObject that could be overloaded to supply a list of interfaces that the dynamic type is emulating. I do not think it is necessary to support base class emulations, but if we could get interface emulation (and handle the runtime dispatching via the existing overloads on DynamicObject) there would be a million things it would open up.

If this cannot make it into the framework, I will probably create an open source project to provide this functionality via runtime code compilation. However, it would be much better if we could get this into the framework as part of 4.0.

MarkSmeltzer wrote  Nov 9 2009 at 7:43 AM  
To follow up on my comment above, I was able to simulate interface emulation using "duck typing". This technique had been around since 2.0 and I was able to get my example to run by manipulating the code from http://www.codeproject.com/KB/cs/nduck.aspx -- all that was required was replacing the hard typed compilation type references with the "dynamic" type, and ensuring that the compiler referenced the Microsoft.CSharp and System.Core assemblies during compilation.

Now, my unit test passes with uses almost identitical code to the code in my previous post:

[TestMethod]
public void TestMethod1()
{
var item = new SomeClass( );
var wrapper = new BindingRedirector<ISomeInterface>( );
var contract = DuckTyping.Implement<ISomeInterface>( wrapper );
var receiver = new BindingReceiver<ISomeInterface>( item, wrapper );

Assert.IsTrue( contract.SomeMethod( ) );
}

My ultimate goal here is to build a messaging stack that is based on the dispatching features provided by dynamics. Once complete, it will offer similar features to WCF, but it will be designed around highly optimized/customizable TCP transports. My personal need is a high performance binary transport, and after all the optimizations we've done in house on our code, now 60% of the time per remote method call is spent in the WCF internals. This penalty for using WCF is unacceptable, but we have already invested a lot into building out our service layer with WCF contracts/etc. and we don't want to throw that away.

So, something like interface emulation will potentially give me access to the best of both worlds. Of course, duck typing will fill the gap if MS doesn't add interface emulation, it would be much cleaner if it were part of the framework.

MarkSmeltzer wrote  Nov 9 2009 at 10:05 AM  
Also, are we going to get a high performance way of converting a normal object into a DynamicObject?

This is essential in cases for when we want to derive from DynamicObject and route everything through to a standard static type. Presently I have to do this routing through reflection and it is slloooowww... surely we can do better!

Updating...
Page view tracker