Databinding Custom Collections C# Source Code

I've received quite a few requests for a C# version of the sample code that came with my article.  So, here is a C# version of the 1.1 custom collection.  If I get inundated with requests I'll port the 2.0 version, but otherwise it's probably not necessary.  There are a couple of changes that you should be aware of.

1.  StudentComparer

In the article I mentioned that I was turning "Option Strict" off on the file containing the StudentComparer so that I could leverage Visual Basic's ability to do type conversions at runtime.  In C# this isn't an option and so the source for the CompareProperties method has changed.  I've added a switch to compare the properties differently based on the type of the property being sorted on.  You'll notice that I've only added string and int.  If you have a custom class with other types that you want to be able to compare, you will need to add to the choices accordingly.

2.  Events

One of the nice things about Visual Basic is that it does a lot of the mundane work for you.  In porting the code tonight I came across one example of  a Visual Basic compiler optimization that can only be described as "GOODNESS".  Let's start by looking at two seemingly identical methods in VB and C#.


This is a simple property that when the value is changed fires a Changed event.  While they look the same, what the C# and VB Compilers do with the Set methods for this property are very different.  So much so that the C# property (as coded) will cause the any changes to fail.  To see what's happening, let's take a look at the Disassembly as C# source code via the magic of Lutz Roeder's Reflector.

Here's the C# version.


And Here's the VB version.


You can see that the VB.NET Compiler was kind enough to wrap the event method in an if to test that there was actually something to call.  The C# compiler expects you to do this yourself.  Now many of you C# coders out there might have spotted the missing if right away.  But the real question is if you should ALWAYS wrap a delegate call in an if statement, why doesn't the C# compiler just do it for you?

 This code has been updated.  Here is the newer version.  Note that this code is still quite old and doesn't use Generics so use it if you like but there are better ways to accomplish these types of collections now.

Download the C# Sample Code

1 Comment

Comments have been disabled for this content.