Francesco's blog

 Saturday, October 29, 2005

First of all, some background on delegate covariance and contravariance in C# 2.0. Let's suppose you have the following delegate definition:

delegate object GetControlData(TextBox ctrl);

Thanks to delegate covariance, this delegate can point to a method whose return value inherits from the delegate's return type. For example, covariance enables a GetControlData delegate to point to any method that takes a TextBox argument, regardless of its return value, because all .NET types inherit from System.Object. The only condition is that the method actually returns something, therefore the delegate can't point to a void method. For example, you can create a GetControlData delegate that points to the following method, because the String type inherits from Object:

string GetText(TextBox ctrl) 
{ return ctrl.Text; }

Delegate contravariance lets you create a delegate that points to a method whose argument is the base type of the argument that appears in the delegate's signature. In previous example, contravariance enables you to create a GetControlData delegate that points to a method that accepts a Control or Object value, because these types are both base types for the TextBox class specified in the delegate signature. For example, the GetControlData delegate can point to this method:

object GetTag(Control ctrl) 
{ return ctrl.Tag; }

It should be evident that covariance and contravariance don't impact code robustness and can't cause type mismatch errors at runtime. Obviously, covariance and contravariance can be combined, thus a GetControlData delegate can point to the following method:

string GetText(Control ctrl) 
{ return ctrl.Text; }

It's important to notice that - even if the target method accepts a generic Control instance - if you call this method through the delegate, you must pass a TextBox argument, because this is the type that appears in the delegate's signature.

You can find more details on what I've explained so far virtually anywhere on the 'Net, with many more examples. It's time to go back to the main reason for this post.

In case you wondered why I used C# for all the examples, here's the reason: Visual Basic 2005 supports neither covariance nor contravariance.

Is that absolutely correct? Well, yes and no. It's true because VB 2005 doesn't support these feature natively, but you can leverage them all the same. It isn't immediately apparent that covariance and contravariance are supported at the .NET Framework level. In other words, they are a feature of .NET 2.0 delegates, not just C# 2.0. In fact, in .NET 2.0 it is possible to use reflection to create a delegate that has both these properties. Here's how you can proceed if you code with Visual Basic 2005. Say you have the following delegate definition and the following method inside a Windows Form class:

Delegate Function GetControlData(ByVal ctrl As TextBox) As Object

Function GetText(ByVal ctrl As Control) As String
   Return ctrl.Text
End Function

VB 2005 doesn't support covariance and controvariance natively, therefore it isn't possible to create a GetControlData instance that points to the GetText method using pure VB code. However, you can get there anyway via reflection, by creating a MethodInfo object that points to the target method and then passing this MethodInfo object to the Delegate.CreateDelegate static method:

' the target method
Dim targetMethod As MethodInfo = Me.GetType().GetMethod("GetText")
' build the delegate through reflection
Dim deleg As GetControlData = DirectCast([Delegate].CreateDelegate( _
   GetType(GetControlData), Me, targetMethod), GetControlData)
' show that the delegate works correctly
Console.WriteLine(deleg(Me.TextBox1))

This code is only slightly slower than the direct creation of the delegate (that you can implement only in C# 2.0), but this is hardly a serious issue, because you typically create a delegate once and use it many times. Another minor problem is that this code can fail at runtime if the method name is mistyped, but on the other hand you would spot this bug the very first time you run the code.

NOTE: I haven't tested this code against the RTM version yet, but under the RC release I found the .NET support for covariance and contravariance isn't perfect. In fact, not all the overloads of the Delegate.CreateDelegate method support this feature. For example, the overload that takes the name of the target method (instead of the MethodInfo that points to the method) causes a runtime error (ArgumentException: Error binding to target method) if you attempt to create a delegate whose signature doesn't match perfectly the target method's signature.

10/29/2005 5:47:43 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
 Friday, October 28, 2005

I was so excited to announce the new version of the dotnet2themax site that I forgot to introduce myself, as is customary in any weblog. On the other hand, if you have attended dotnet2themax.com in the past, odds are that you already know me, perhaps because you've read one of my books or one of my articles on programming magazines. But I will summarize my professional life here, if only to provide links to other places where you can find more interesting material.

I live and work in Bari, Italy, but I often travel to speak at conferences such as VSLive!, WinDev (US), DevWeek (UK), TechDays (Switzerland), and a few others.

I am one of the two Italian MSDN Regional Directors and in the last two years I have served as the chairman for Windows Professional Conference, the largest Italian conference for developers, and routinely speak at DevDays and other Microsoft events in Italy since 1998. I have been giving classes for Wintellect in the US until mid-2004, when I decided not to spend abroad 5 or 6 months of each year.

In 2002 I founded Code Architects, a software company that focuses on .NET and Microsoft technologies, together with Giuseppe Dimauro (the other MSDN Regional Director for Italy). Code Architects provides training and consulting services for many Italial government agencies and large companies, including Microsoft. Code Architects markets a line of programming tools that I authored (or co-authored), including CodeBox, Form Maximizer, and the award-winning VB Maximizer. The Code Architects Team include some of the most skilled .NET experts in Italy. If you can read Italian, you might find a lot of interesting stuff in our Team Blog.

I wrote about 80 articles for Visual Studio Magazine (formerly Visual Basic Programmer's Journal), with which I collaborate since 1996, and also wrote a couple of articles for MSDN Magazine and for developer's sites such as DevX. For example, you can go here to read nearly 300 tips and short articles I wrote for DevX, mostly on VB6.

I don't write only for US magazines, though. I wrote my first article back in 1983, then I wrote dozens of columns for Computer Programming, the leading Italian magazine for developers. In 1995 I founded Visual Basic and .NET Journal (formerly Visual Basic Journal), the only Italian magazine entirely devoted to .NET Framework programming.

 


English

Italian

While I still am the editor-in-chief of my own magazine, in recent years I decided to write fewer articles to focus on my books and my own vb2themax.com Web site, which I founded in 1999 and that a few years ago was expanded into dotnet2themax.com to match the new C# and VB.NET contents. This site is now sponsored by Code Architects, together with the Italian web sites dotnet2themax.it and ugisharepoint.it.

Microsoft Press published my first book in 1999. Since then Programming Microsoft Visual Basic 6 has sold around 150,000 copies all over the world, including translations to Italian, Japanese, Chinese, Korean, and Spanish, and continues to sell more than many VB.NET books. In 2002 I wrote Programming Microsoft Visual Basic .NET, which the next year was upgraded into Programming Microsoft Visual Basic .NET 2003, a 1400-page textbook that cover virtually everything you need to know about VB.NET and the .NET Framework. It has been one of the VB.NET bestseller and as of today it nearly alwways appears in Amazon's Top Ten list for Visual Basic and .NET books. I also co-authored Applied Microsoft .NET Framework Programming with Microsoft Visual Basic .NET (with Jeffrey Richter) and the newer Practical Coding Guidelines and Best Practices for Visual Basic .NET and C# Developers (with Giuseppe Dimauro), a collection of over 700 rules and tips for writing robust and efficient .NET applications.

While Visual Basic is still my pet language, I write a lot of C# code as well. I am especially interested in programming techniques, algorithms, optimization, .NET internals, client-side (Windows Forms) and ADO.NET programming. I love to write addins, macros, code generators, and other tools that can make programming a more pleasant (and faster) experience, and I'll use this blog to share my findings with you all.

What else? I love music - a bit of everything, but especially jazz and fusion - and in my previous life I was even tempted to become a professional musician, until I realized that programming can be as much fun. I played my alto sax with many local combos and orchestras, but I probably reached by peak - on the fun side, at least - with Don Box's Band on the Runtime. If you are among the few millions who never listened to the Band, you can grab a video here or here. You can find some lyrics here and here.

Books | Misc
10/28/2005 4:25:13 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
 Thursday, October 27, 2005

If you're reading these lines you already know that we have completely renovated the .NET-2-The-Max site. We have a new layout, new material, and new blogs. We have less contents, too. Yes, we've decided to drop some sections from our site. Let me explain why.

When we launched the original vb2themax.com site in 1999 it was hard to find quality-level material on developers' sites. Most sites solicited tips and code samples from visitors and published it, in most cases without editing it for accuracy. Thus, we took the opposite route and decided to publish just our own material and only the best contributions from our readers. This approach and the fact that we have published new material each and every week for three years made our site very popular among VBers. (SQL Server Magazine put vb2themax in the top ten developers' site, together with first-class sites such as MSDN Online and DevX.)

More recently we lauched dotnet2themax.com. We dropped all VB6 contents to focus on .NET exclusively. The new site offered tons of links to external articles - that were categorized and searchanble, and enabled readers to filter both the index and individual articles' contents to see the material related only to VB.NET or C#. In spite of these new features, the site was basically similar to the original vb2themax and was conceived as a single-stop-shop from where developers could start their explorations.

Today, however, finding great contents on the Web is easier than ever. Most magazines are available online and for free, many Microsoft developers reveal all the .NET secrets in their blogs, and you can always use Google to discover programming gems hidden in a site or a blog you never heard before. There's no more need for a site like what dotnet2themax used to be. No need for topic categories and an internal search engine, for example. And above all, no need to update the web site on a regular basis, as if it were an online magazine.

In the new dotnet2themax.com site, Marco Bellinaso and I - and whoever will join us later - will be telling our discoveries in the .NET fields we are more familiar with, such as VB.NET and C# languages, programming techniques, ASP.NET, Windows Forms, Sharepoint, and optimization techniques. We will write our blog as frequently as possible, publish code samples and articles, upload our tools, and anything we think can be useful or interesting for you developers out there.

Happy reading!

Francesco

10/27/2005 10:05:02 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
 
Get RSS/Atom Feed
RSS 2.0 | Atom 1.0
Search in the blog
Archive
<October 2005>
SunMonTueWedThuFriSat
2526272829301
2345678
9101112131415
16171819202122
23242526272829
303112345
Categories

Powered by: newtelligence dasBlog 1.8.5223.1