OdeToCode IC Logo

Generic Gotchas

Thursday, July 15, 2004 by scott
The introduction of generics will be a welcome addition to C# and VB in 2.0, except the change is little more disruptive than I would have thought. Consider the current use of Hashtable:

Hashtable lastNames = new Hashtable();
lastNames.Add("Beatrice", "Arthur");
lastNames.Add("Lucille",  "Ball");
 
object name = lastNames["Audrey"];
if (name == null)
{
    lastNames.Add("Audrey", "Hepburn");
}

Now here is how it might look after an porting to use the generic type Dictionary<K,V>:

Dictionary<string, string> lastNames;
lastNames = new Dictionary<string, string> ();
lastNames.Add("Beatrice", "Arthur");
lastNames.Add("Lucille", "Ball");
 
// the next line throws KeyNotFoundException
string name = lastNames["Audrey"];
if (name == null)
{
    lastNames.Add("Audrey", "Hepburn");
}

In Beta 1 the indexer throws an exception if the given key does not exist in the collection. If this is not desirable behavior, you can use the ContainsKey method to check safely if a given key exists. The current behavior makes porting code based on Hashtable to Dictionary<K,V> a bit trickier.

I think the current behavior is justified. What would happen with a Dictionary of integer values when you pass a key that does not exist? There is no possibility of returning null for a value type, and returning a default value (0) seems misleading and bug-prone.

Another gotcha is in the second sentence of the documentation for every generic type:

This class is not CLS-compliant

The question is: Do I care?

I’ve read articles about how being CLS compliant will allow for interoperability with a wider range of .NET languages. This could be important for library designers targeting the 0.4% of the market using Cobol.NET and Fortran.NET. I did a quick test to see the impact on the other 99.1%. First, I put the following in a C# class library:

public class Class1
{
    public Dictionary<string, int> GetDictionary()
    {
        Dictionary<string, int> foo = new Dictionary<string, int>();
        foo.Add("test", 2112);
        return foo;
    }
}

Next, a quick VB program to use the C# class. (I was a little worried I might have to dig to find generics syntax for VB, but my fingers had a spasm and intellisense auto-completed the entire program. It was amazing. Did I mention my cat wrote a Tetris knock-off with Whidbey last week?).

Sub Main()
    Dim c As New ClassLibrary1.Class1
    Dim bar As Dictionary(Of String, Int32)
    bar = c.GetDictionary()
    Console.WriteLine(bar("test").ToString())
End Sub

It all just works.

For the applications I work on, generics are powerful enough to sacrifice CLS compliance. I imagine this will be the case for the majority of developers. Porting an existing codebase heavily into collections to the generic types won’t be automatic, but nothing to sweat over if all the unit tests are written, right?

Book Shopping

Wednesday, July 14, 2004 by scott

I've been running low on reading material, so I decided it was a good time to go book shopping.

One title that has caught my eye with it's quirkiness is Coding Slave. Judging by the web site, this should be entertaining.

I also found out Neal Peart has a new book on the way. I'm just wondering if I should pre-order through Amazon, or wait until the Rush tour hits Virginia this August. Pehaps some copies might be available for sale there. Decisions, decisions.

More Fun With Generics: Action, Converter, Comparison

Sunday, July 11, 2004 by scott
As a follow up to yesterday’s blog about the Predicate<T> delegate, I wanted to try out the three additional delegate types in the generics area.

First, a new type to work with:

class Person
{
   public Person(string name, DateTime birthday)
   {
       this.name = name;
       this.birthday = birthday;
   }
 
   public string Name
   {
       get { return this.name; }
       set { this.name = value; }
   }
 
   public DateTime Birthday
   {
       get { return this.birthday; }
       set { this.birthday = value; }
   }
 
   string name;
   DateTime birthday;
}

The Comparison<T> delegate represents a method used to compare two types. If you have ever needed to define an entirely new type deriving from IComparer just to tell Array.Sort how to compare two objects, you’ll appreciate the brevity in the following sample.

List<Person> list = new List<Person>();
 
list.Add(new Person("Alex", DateTime.Now.AddYears(-30)));
list.Add(new Person("Neal", DateTime.Now.AddYears(-20)));
list.Add(new Person("Geddy", DateTime.Now.AddYears(-25)));
 
list.Sort(
      delegate(Person x, Person y)
      {
        return Comparer<DateTime>.Default.Compare(x.Birthday, y.Birthday);
      }
 );

Next is the Converter<T,U> delegate. Use this delegate to convert each object of type T in a collection to type U.

List<int> yearList;
yearList = list.ConvertAll<int>(
        delegate(Person p)
        {  
            return p.Birthday.Year;
        }
   );

Finally, there is the Action<T> delegate. Use this delegate to perform an action with each object of the collection.

yearList.ForEach(
        delegate(int year) { Console.WriteLine(year); }
    );

I am generally grouchy about any new language feature until I can write some code and figure out its purpose in life. Generics I knew would be a hit, and after writing this code I’m starting to warm up to anonymous delegates.

Generics and Predicates

Saturday, July 10, 2004 by scott
What will be an elegant technique to remove objects matching a condition from a List in C# 2.0?

If the following code finds a match, we’ll find out it’s a no-no.

foreach (string s in list)
{
    if (s == "two")
        list.Remove(s);
}

In VS2005, the code creates this friendly little dialog.

C# 2.0 introduces generics, and with generics come predicates. A predicate returns true when an object meets a set of conditions, otherwise false. A method like List.RemoveAll will run each object in the collection through a given predicate to test each object for a match. When the predicate returns true, the method removes the object from the collection. The nifty thing is, you can write the predicate as an anonymous delegate:

list.RemoveAll(
    delegate(string s)  { return s == "Two"; }
);
 

Alternatively, you can keep your logic inside a named method.

static bool MatchTwoPredicate(string s)
{
    if (s == "Two")
        return true;
    return false;
}

// and later . . . 
 
list.RemoveAll(MatchTwoPredicate);

I feel either technique is easier on the eyes when compared to STL and functors in C++. Then again, I should be sleeping right now instead of blogging.

Does Michael Powell Have The Ugliest Blog On the Planet?

Saturday, July 10, 2004 by scott

While veering through Yahoo news this evening I came across the headline: “FCC Boss Launches Blog Aimed at High-Tech Industry”.

I was stunned.

For the first time ever I read about a new blog from a source outside the blog world. Usually you find out about these sorts of thing by plowing through 25 insightful blog entries which read: “so and so is blogging – subscribed!”.

In true Yahoo / Reuters fashion, however, the news article didn’t contain an actual link to the blog, but links to news and websites about the FCC. At the very bottom of the article, they put in the URL, but not in a hyperlink. I cut and pasted the URL into IE.

I was stunned.

I really thought I had reached the wrong server. I see a big broken banner on the top because ActiveX controls are disabled for the Internet zone. Advertisements and menus appear randomly on the page, and there is a huge gap of whitespace to scroll through before blog entries appear.

[update: i've been informed this is because I also have JavaScript disabled in the Internet zone. DUH! Ah, the pleasures of running Win 2003 Server and hardened security on a desktop machine. Still - the colors give me a headache.]

Then I reached the bottom of the page, which included more advertisements from Sun, IBM, and AOL. On a hunch, I viewed the page in Firefox. Suddenly, the layout improved. Menus aligned. Caverns of white space turned into proper half inch borders.

The colors still give me a headache, but it’s hard to cram 22 advertisements on a page without looking like a dryer full of checkered golf clothes.

Interesting that the head cheese of the FCC has a blog that doesn’t render well in the most popular browser on the planet. [update: ok, maybe it does render with everything enabled, but it's still UGLY!]

Latest OdeToCode Articles

Thursday, July 8, 2004 by scott

ASP.NET 2.0 and Site Maps

Thursday, July 8, 2004 by scott
I hereby interrupt the “week of the malcontent” with the “evening of possible enlightenment”.

The provider design pattern in ASP.NET 2.0 is sweet. I’ve been toying around in the SiteMapProvider area since the first CTP. There is an XmlSiteMapProvider which let’s you describe the navigation and layout of your web site in an XML file like so:

<?xml version="1.0" encoding="utf-8" ?>
<siteMap>
  <siteMapNode title="Home" url="Default.aspx" >
    <siteMapNode title="Products" url="Products.aspx">
      <siteMapNode title="Seafood" url="Seafood.aspx"/>
      <siteMapNode title="Produce" url="Produce.aspx"/>
    </siteMapNode>
    <siteMapNode title="Contact" url="Contact.aspx">
      <siteMapNode title="Email Us" url="Email.aspx"/>
      <siteMapNode title="Phone List" url="Phones.aspx" />
    </siteMapNode>
  </siteMapNode>
</siteMap>

Without writing a line of code (just some drag and drop operations), you can give all the pages in your site a tree view of the site hierarchy and a bread crumb control:

What if your site navigation comes from a database table?

NodeID URL           Name     ParentNodeID 
------ ------------- -------- ------------ 
1      Default.aspx  Home     0
2      Products.aspx Products 1
3      Seafood.aspx  Seafood  2
4      Produce.aspx  Produce  2
5      Contact.aspx  Contact  1
6      Email.aspx    Email    5
7      Phones.aspx   Phone    5

All you need to do is derive from the abstract class SiteMapProvider and override a handful of methods, like GetParentNode and GetChildNodes. These methods can be straightforward to implement with a few pre-built collections of type Dictionary<string, SiteMapNode>. SiteMapNode objects represent the nodes in the site map, while a Dictionary is one of the exciting new classes from the System.Collections.Generic namespace, which you can use to build strongly typed collections.

One you have some code querying SQL Server and implementing the SiteMapProvider methods, you just need to tell the runtime about your new provider via a config file:

<siteMap defaultProvider="MySqlSiteMapProvider" enabled="true"> 
  <providers> 
    <add name="MySqlSiteMapProvider" type="SqlSiteMapProvider"
         connectionStringKey="ConnectionString"/> 
  </providers> 
</siteMap> 

You can have multiple providers for a site. If half of the site navigation information comes from XML and the other half from the database, that’s quite possible. It will be interesting to see what other providers come out. I'm sure SQL, and File System providers will be in demand.