Showing posts from November, 2008

.NET 2.0 Extension Methods

I regularly write programs in C# on Visual Studio 2008. The default Framework for the environment is 3.5. But sometimes I must re-target 2008 to Framework 2.0. Is it possible to take advantage of the new "Extension Method" language feature of 2008 when required to target 2.0? This is a good question and applies to more than the extension methods. But for now, let's answer the question for extensions.


But, you need to do some of the work yourself. The compiler's support for extension methods is really unconnected with Framework 3.5. But maybe you've seen the error...

Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to System.Core.dll?

To write an extension, you need the ExtensionAttribute somewhere, anywhere. The compiler is looking for it in the System.Runtime.CompilerServices namespace which is in System.Core.dll. The 2.0 …

An Interesting Delegate Usage

An interesting thing happened while I was surfing the MSDN C# forums. I was completely thrown for a loop when I came across some code posted by a regular contributor. It went something like this...

private void ACallBackFunction()
this.Invoke(new ThreadStart(ACallBackFunction));
this.label1.Text = "Something or other";

The programming pattern should be very familiar to those using threads, because this is how a child thread updates the GUI (only the thread on which the GUI is created can update the UI). But, what seemed very strange was the use of "new ThreadStart(...)". I thought, what does a ThreadStart() delegate have to do with this operation?

The answer is ... nothing. But the application is none the less interesting. Here, the programmer decided to draw from a handy delegate in the C# tool chest just to get that required delegate to call "Invoke()" with. "ThreadS…