Saturday, March 29, 2008

There is a nice little base class hidden inside System.Collections.ObjectModel namespace. Its name is KeyedCollection. Its there to solve all those situations when we need a collection where items are to be unique, a "collection whose keys are embedded in the values" - as MSDN describes it.

As nice as the class is, there is one problem. It is abstract. The reason it is abstract is the GetKeyForItem method. For each type what we need a unique collection, we need to create a new class, inherit it from the KeyedCollection and override that one method. I think that's a bit of a waste of time and needles complexity in most cases. Fortunately, there is hope.

Enter KCollection. The idea behind it is to use Lambda Expressions where we had to override the GetKeyForItem method before. Sample code should explain everything:

class KCollection<TKey, TItem>  : KeyedCollection<TKey, TItem>
{
    Func<TItem, TKey> getKey;
    public KCollection(Func<TItem, TKey> getKey)
    {
        this.getKey = getKey;
    }
    protected override TKey GetKeyForItem(TItem item)
    {
        return getKey(item);
    }
}

And usage looks as follows:

KCollection<int, Client> kcol = new KCollection<int, Client>(c => c.Id);

Where Client is a simple class:

class Client
{
    public int Id;
    public string Name;
}

Of course we could achieve similar functionality using .NET 2.0 and delegates, I think Lambda Expressions are just nicer.

Saturday, March 29, 2008 2:44:47 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [2]  | 

I've never liked VB.NET. Probably because I was (un)fortunate enough to work with VB6 for 2 years, even though .NET and C# were already there. Nevertheless I'm aware that VB.NET tends to offer some very useful syntax not found in C#.

One thing that I've recently discovered is the ability to specify a "Key Properties" when defining an Anonymous Type.

Syntax for the declaration is more or less as follows:

Dim person = New With {Key .Id = 1, .Name = "John"}

Notice the Key keyword before Id property. Now the interesting thing is that VB.NET compiler generates the Equals method that compares objects for equality, using only the Key Properties as opposed to comparing all properties when code is generated by C# compiler.

Now tell me that VB.NET is slower than C#.

More on the topic can be found on MSDN article on Anonymous Types in VB.NET, in section on Key Properties of course.

Saturday, March 29, 2008 11:59:11 AM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 
 Friday, March 14, 2008

Internet Explorer Enhanced Security Configuration - don't you just love it?

Is there anything worse that Microsoft has given us over last few years? I really doubt it.

Friday, March 14, 2008 5:29:12 PM (Central European Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [2]  |