November, 2003

  • Eric Gunnerson's Compendium

    Generics Algorithms


    A few weeks ago, Anders walked into the C# design meeting and said, "I think I have a way to get generic algorithms to work with our current support", and then proceeded to outline a scheme on the whiteboard. I dutifully copied it into our design notes (after being away from the design process for a couple of years, keeping the notes up to date is my big contribution).

    Today, I was home taking care of my sick daughter, so I spent some time playing around with his idea.

    The basic idea is to create a generic class that defines the operations that can be performed on a data type, and then create specialized implementations. Something like:

    public abstract class Calculator<T>
        public abstract T Add(T a, T b);

    and then derive a specific class from it:

    namespace Int32
        public class Calculator: Calculator<int>
            public override int Add(int a, int b)
                return a + b;

    We'll be using Int32.Calculator to perform operations on ints. We could extend thte calculator class to perform more operations, and create implementations to deal with different types. So that's the first part of the scheme. It's somewhat reminiscent of template specializations in C++, but it's not

    We can now define a library to use it: 

    class AlgorithmLibrary<T> where T: new()
        Calculator<T> calculator;

        public AlgorithmLibrary(Calculator<T> calculator)
             this.calculator = calculator;

        public T Sum(List<T> items)
            T sum = new T();

            for (int i = 0; i < items.Count; i++)
               sum = calculator.Add(sum, items[i]);

           return sum;

    This class encapsulates algorithms inside of it. When we want to use it, we can write:

    AlgorithmLibrary library = new AlgorithmLibrary<int>(new Int32.Calculator());

    I should perhaps explain how this works. When we construct library with int as the type argument, that means that constructor is looking for a Calculator<int> rather than a Calculator<T>, which is convenient, since that's the class we passed into it.

    Ultimately, we end up with a version of Sum that uses the int calculator to do its operations.

    That gives us a workable scheme, though it is a bit ugly because we have to create the calculator and pass it in. The neat way that Anders came up to get around this is to use a pattern-based approach, and use reflection. We first look for the calculator class off of the type, and if we don't find it, we look in the standard place. This means that you can have the AlgorithmLibrary constructor find the right calculator for us.

    This all worked out fairly well. I'd show you the whole code, but I'm not quite happy with it, and I'm not sure it would run on the PDC bits, so you'll probably have to wait for a while. Here's a sample of using it:

      List<double> ld = new List<double>();


      AlgorithmLibrary<double> cd = new AlgorithmLibrary<double>();

      Console.WriteLine("Sum is {0}", cd.Sum(ld));
      Console.WriteLine("Mean is {0}", cd.Mean(ld));
      Console.WriteLine("SD is {0}", cd.StandardDeviation(ld));

    One concern with this approach is performance. I did a few quick benchmarks, and for lists, this approach takes about 50% longer than coding it by hand. For arrays, it's about twice as slow. I think the major problem is the virtual function, but there may be a way to make that faster.


  • Eric Gunnerson's Compendium

    Public fields vs properties


     If you search on MSDN, you won't find any general C# coding guidelines. When people have asked how they should write their code, they often get pointed to the class library design guidelines. There is lots of good advice there, but not all of it applies universally.

    One of the guidelines says:

    • Do not use instance fields that are public or protected

    it goes on to say that this is important because properties don't version well.

    Some people have taken this as an absolute rule, so I've been seeing lots of code that uses properties on every class. If you don't need the versioning advantages of properties, you don't need to spend the time writing lots of trivial properties (those where the getter and setter don't do anything special).

    In fact, I'll say that a bit stronger. You probably shouldn't use properties unless you need them, as it takes more work and makes your classes harder to read and maintain.

    So, when should you use properties that you don't need? My suggestion is to only use them at versioning boundaries. If a class and the classes that use it are always compiled together, than properties don't buy you any advantage. If they are compiled separately, then using properties instead of fields looks like a better idea.

    Or, to put it another way, writing trivial properties makes sense at the locations where your component interfaces with other components.




  • Eric Gunnerson's Compendium

    C# Performance


    If you're concerned about performance, you should read Rico Mariani's blog.

    Rico is an architect on the CLR team, and, coincidentally, is one of the developers who interviewed me way back in 1994.


  • Eric Gunnerson's Compendium

    Quiet CPU Fans?


    I recently built a music system for the ski cabin (you can only listen to Infinity so many times). It's a Micro-ATX system with a 40Gig drive, a CD ROM, and 256M of memory. More than enough for music. It runs the same custom MFC application that I use for my music system at home, and I'm using an old PocketPC as the remote control.

    The system works great, except that the CPU fan that I got at my local PC store (the original one I got was too tall) sounds like a hair dryer. So, I'm shopping for a new CPU fan that's quiet.

    The search has been a bit confusing, so I'm looking for some help. The CPU is an Athlon 1.3GHz, and the fan needs to be not much bigger than the "small heatsink" size (ie about 3" square), and it can't be too tall (about 3" max).


  • Eric Gunnerson's Compendium

    An Introduction to C# Generics


    An Introduction to C# Generics

    By one of my friends, Juval Lowy, founder of IDesign.



  • Eric Gunnerson's Compendium

    Tantric snacking...


    This afternoon after lunch I ambled over to our admin's office in search of a small snack. I opted for some m&m's brand chocolate candies with peanuts. As I ate the 7 m&m's that were in the package, I noticed that the package was labelled "Fun Size".

    Others may disagree, but personally, I don't think that 7 m&m's produce an experience I would label 'merry' or even 'jocular', much less "fun", but I'm willing not to quibble on that point, especially when a far more important issue looms.

    What do you call the larger sized packages? What word do you use for something that is more fun than fun?

    There really is no English word that works. You have to move to more philosophical descriptions. The one that first springs to mind is "transcendent", which has all the right connotations, but unfortunately lacks the popularity of "tantric" (as demonstrated by the relative sales ranks of the top books with each title on Amazon).

    So, "Tantric snacking" it is...

    If you don't like this kind of entry, you may comfort yourself that at least I'm not writing about my sump pump...

  • Eric Gunnerson's Compendium

    What are you planning on using Visualizers for?


    One of the big new features for VS in Whidbey is the ability to write custom visualizers for your classes. Visualizers are written in managed code, and present whatever interface they want to view and edit the data.

    There are some obvious place where we're going to use this - if you've ever tried to look at the data in a dataset, you know that there's a lot of room for improvement. But we're interested in how you're planning on using it. Specifically:

    1) How many visualizers do you think you will write?

    2) What kind of objects will you write visualizers for?

  • Eric Gunnerson's Compendium

    New CLR Profiler release


    From Jan Gray's blog (Jan is another of the Perp team members), a new release of the CLR Profiler. This tool, which used to be known as the "Allocation Profiler", was written by Peter Sollich, who also happened to be a member of the C# design team for a while.


  • Eric Gunnerson's Compendium

    Have you ever asked yourself "Why am I here?"


    I'm not talking about the metaphysical question of whether there is a purpose of existence. I'm speaking of a more concrete concern. Why am I here, sitting at my desk, working on a computer, at 1:48 PST, on a late November day?

    When I could be here...


  • Eric Gunnerson's Compendium

    Book Review: The Salmon of Doubt


    Like many people, I was saddened when I heard about Douglas Adams' death last May.

    Of course, I had read Hitchhikers many years ago, and had also read his Dirk Gently series. I also had the unique (well, not *truly* unique) privilege of hearing him speak when he did a talk at Microsoft a few years ago.

    I recently came across a copy of The Salmon of Doubt, which I would describe as a brain dump of a bunch of useful things that Douglas had on his computers at the time of his death. There are a lot of short articles and essays, and then a few chapters from a never published Dirk Gently book. The articles and essays are varied and interesting, and the chapters, while a bit uneven, are definitely good stuff.

    Overall, I liked the book a lot, and found out a lot about Douglas that makes me more convinced that the world has truly lost a unique soul.

    One especially poignant part of the book is the order of service for his memorial. If you have Richard Dawkins speaking at your memorial service and David Gilmour performing "Wish You Were Here" (my absolute favorite Floyd song), you're hangin' in the right crowd in my book.

  • Eric Gunnerson's Compendium

    Note to my younger self


    Note to my younger self: Eat better.

    There won't be any programming content here, so you may choose to ignore this post, though you may regret it in a decade or two. Don't say I didn't warn you.

    A few weeks before PDC, I started have a problem of a very personal nature. That's right, I had an outbreak (incident? flare up? episode?) of hemorrhoids. It's not something you generally want to publicize, and in fact, I didn't talk about it. I've decided to blog about it, for a simple reason:

    If somebody had told me what I'm going to tell you when I was in my 20s, I would have had the opportunity to change my habits.

    Most Americans eat less than half the fiber they should, which also means they're probably eating fewer vegetables than they should be. Trust me when I tell you that you don't want this condition. And since over 50% of Americans have it at one time or another, the odds aren't good. A decent diet can make it unlikely you will ever have to deal with it. Not to mention the other benefits.

    After my first "encounter" about a decade ago, I changed my diet a fair bit and got better, but after the recent episode - and a fairly miserable few weeks, including a unhappy week at PDC, I decided to see a specialist, who last Tuesday did a small bit of surgery. After which I found out an interesting pharmaceutical fact.

    Well, perhaps "found out" isn't really the right term. Something like, "had beat into me over five increasingly miserable days".

    My doctor had written me a prescription for Vicodin, the trade name for Hydrocodone, an opiate that's more potent than morphine, to help control the pain. It is wonderful against pain. But it is not without side effects.

    If you go to a drug website, you'll find a list of side effects. There are a lot of fun "mind altering effects", which I like to call "crazy thinkin'", but the most important one is the second one. Apparently opiates are well known to utterly and completely shut down the later stages of digestion. For me, two vicodin did me in. Saturday night found me in the emergency room treating that condition, and today I'm feeling better than I have in the last 6 months.

    The choice is yours.



  • Eric Gunnerson's Compendium

    C# Sneak Preview Document


    We've put a C# Whidbey Sneak Preview document on the dev center. It has a good overview of the new cool stuff that will show up in Whidbey.

    Note that this isn't an exhaustive list; there are some things that will show up that aren't in the document.

  • Eric Gunnerson's Compendium

    C# Team Chat in 20 minutes (2PM PST)

  • Eric Gunnerson's Compendium

    Barbecued TurkeyAlt


    Reading Chris Anderson's post about Deep Fried Turkey got me thinking...

    I've been barbecuing turkey for about 5 or 6 years now, and in the spirit of sharing, here's my recipe:


    • Bird, 1, large. We generally have a lot of people over (~15), so this means somewhere around a 22 pound bird. I prefer a fresh turkey over a frozen one, but it's up to you.
    • Grill, Weber, charcoal, 22" size. Some people use gas barbecues, but I'm very much a traditionalist. It helps if it has the fold up edges so you can get under the grill easily.
    • Briquets. I'm a Kingsford man. Some swear by chunk charcoal, but I prefer briquets.
    • Roasting tray, 8" x 10"
    • Thermometer. You can use a normal dial-indicator kind, but I prefer a remote digital one. If you use a dial one, cover the dial with aluminum foil.
    • Wood chips. Turkey has a fairly mild flavor, so you want a subtle wood. I usually use a fruitwood, like apple or cherry. This year, I used alder (because I forgot my apple wood and had some alder logs), which my wife liked better but I didn't like quite so much. You want to avoid strong woods, such as mesquite, or hickory (my least favorite wood).
    • Two "turkey lifter" thingies. Look a little like goalposts.


    1. Prepare the bird. At the minimum, you'll want to remove the "yuckola blobs" from the inside. Some people like to brine their turkey before hand. I think it helps a little in moistness, but the barbecue will give you a fairly wet heat anyway, so it's not that much of an issue. Rub on butter and add salt/pepper as desired.
    2. Start around 30 briquets.
    3. Put the briquets on the edges of the grill, with the roasting pan between them.
    4. Put the bird on the grill.
    5. Put the thermometer into the thickest part of the breast.
    6. Lift up the edge parts of the grill, and put some chips on the briquets.
    7. Close the lid

     Now, every 30-60 minutes, open the lid, add briquets to keep the amount constant, and add wood chips if desired. Less is more on the wood chips - I usually don't add any after the first hour.

    Continue until it reaches the desired temperature. I've typically gone to 165 degrees, but I notice that Alton Brown says 161 degrees.

    Remove from the grill, and use the drippings to make gravy. Carve the turkey, and enjoy.


  • Eric Gunnerson's Compendium

    As the weather turns colder, a young man's thoughts turn toward...


    Holiday lights.

    The first house that my wife and I bought was in a development with an active homeowner's association. The first year, we got a flier from the association that said:

    Holiday decoration contest

    $100 first prize
    $50 second prize
    $25 third prize

    With hundreds of houses in the development, we didn't figure we had any chance, but we did put up a few more lives than usual, and somehow won second prize.

    A monster was born.

    After a trip to Point Defiance Zoo's excellent Zoolights got me thinking about animated light displays. I had wanted to do some microcontroller programming, but didn't have an application until now. I hooked up with one of the robotics experts in my group, and bought the parts to build a BotBoard, and did the hardware and software for an 8-channel light sequencer.

    The sequencer was destined for a Santa animation. It starts with some flashing landing lights, and then Santa and his reindeer appear. A few seconds later, Santa and the presents move onto the roof, then up to the chimney, then disappearing down the chimney. Pause, and the sequence repeats.

    It was a lot of fun to write the software - the BotBoard runs a Motorola 68HC11E2 processor that is programmed over the serial port. A very cool processor with built-in timers and other useful subsystems, but it's a 8-bit architecture, and you get to program it in assembly language (you can find compilers if you want). Debugging is interesting...

    So, we got that project done, but only won third prize.

    A few years passed, and I had some leftover BotBoards, so I built the second controller. This one was a 16 channel controller, but uses the same basic architecture. It runs a 10' tree made up entirely of lights (well, lights, electrical conduit, and a whole lot of wire).

    For my most recent application, I wanted to do something different. One of the things that I found annoying was that the lights that outlined the house were white, and static. I wanted some thing different. I could have built another sequencer, but that would have given me a quick switch between colors. I wanted something more subtle.

    To do this, you have to get into dimming. That makes the project tougher, as you now need to have tight control on the timing to get it to work. It's also a bit harder to fit everything into the 2K of EEPROM and 512 bytes (yes, bytes) of memory you have.  This one took me a while, but ultimately gave me a very good project.

    In fact, I was able to write an article on it for Nuts & Volts magazine.

    So, as Thanksgiving approaches, I need to get ready to put up all three of the animated displays and a few thousand over lights. The total number of lights is around 13,000.

    I've been hoping to spend some time building some new sequencing - perhaps one that can be driven over a serial port.

    If you happen to live in the Bellevue area, you can stop by. I'm going to try to post some pictures when it's all up and running.

    Oh, and if you think I'm out of control, take a look at this, and of course, the granddaddy of them all, PlanetChristmas. 35,000 Lights.  Here's a video.

  • Eric Gunnerson's Compendium

    C# PDC Sessions now on line


    The C# PDC sessions are now online. Experience what we saw at PDC last month, minus the pervasive campfire smell.

    You can either download the slides or watch the presentation (using Microsoft Producer, IIRC). I'd suggest watching:

    TLS320 - Visual C# "Whidbey": Language Enhancements (Anders Hejlsberg)

    TLS321 - Visual C# "Whidbey": IDE Enhancements for the C# Developer (Scott Wiltamuth and Anson Horton)

    TLS343 - Visual Studio "Whidbey": Advanced Debugging Techniques (Habib Heydarian)

    Oh, and I understand that there was some sort of announcement about some "OS thingy" at the conference - you might want to look at those presentations as well.


  • Eric Gunnerson's Compendium

    C# Team Chat: New Features in Whidbey


    The C# team is hosting a chat on MSDN next week discussing the changes in Visual C#, including both language changes and IDE changes.

    November 20, 2:00 P.M. Pacific time/5:00 P.M. Eastern time - You can find more information about this chat on

Page 1 of 1 (17 items)