1. Stupid .NET Tricks #4

    August 30, 2007 by Craig

    Consider this code:

    public delegate void AnAction();
    
    private static List getActions() {
      List actions = new List();
      for (int i = 0; i < 10; i++) {
        actions.Add(delegate() {
          Console.WriteLine("i is:" + i);
        });
      }
      return actions;
    }
    
    static void Main(String[] args) {
      List actions= getActions();
      foreach (AnAction action in actions) {
        action();
      }
    }
    

    If you run this code, you do not get a series of lines stating “i is: 0” through “i is: 9”. You do not get any errors, warnings, or exceptions at either compile or run time either.

    What you get is this:

    i is: 10
    i is: 10
    i is: 10
    i is: 10
    i is: 10
    i is: 10
    i is: 10
    i is: 10
    i is: 10
    i is: 10
    

    When the delegate is added to the collection of delegates, it’s using the actual variable “i”, not the object that the variable is referencing at the time. (This applies for both reference and value types.) By the time the delegate collection is accessed and the actions are invoked, “i” has the value “10” (which, by the way, is outside the normal operating range of the loop), even though “i” is no longer in “normal” scope.

    This almost makes some sense, even though I think it’s counter-intuitive (and thus bug-encouraging). The .NET inventors had to choose between referencing the variable and referencing the value; there’s use cases for both. However, it starts getting really strange when you make a copy of the variable, as in this replacement code:

    private static List getActions() {
      List actions = new List();
      for (int i = 0; i < 10; i++) {
        int x = i;
        actions.Add(delegate() {
          Console.WriteLine("i is:" + i + ", x is:" + x);
        });
      }
      return actions;
    }
    

    i is:10, x is:0
    i is:10, x is:1
    i is:10, x is:2
    i is:10, x is:3
    i is:10, x is:4
    i is:10, x is:5
    i is:10, x is:6
    i is:10, x is:7
    i is:10, x is:8
    i is:10, x is:9
    

    Upon invocation, the delegate references the variable "i" but the value of "x". How and why it makes that choice is beyond me.


  2. Is this Paige Worthy?

    August 29, 2007 by Craig

    Freakonomics Blog is having an impromptu contest to find the best real-life aptonym: a personal name that accurately describes the bearer or their profession. The example Dubner gives is a magazine fact-checker named “Paige Worthy.”

    It took me about 10 minutes before I realized that I myself am a contender since I like to hike in the mountains.


  3. Harnessing the Power of Stupid

    August 24, 2007 by Craig

    I once worked in a bank, making loans to small business start-ups. Our rule of thumb was that 90% of new businesses fail. The exceptions were franchisees and pizza places. But we saw no shortage of people willing to mortgage their homes to start their own sporting good stores and boutique dress shops, despite the 90% chance of failure. Without clueless optimists, the economy would grind to a halt. My own career has been a long string of failures and a few notable successes.

    I understand the math of capitalism, and how the few successes are so large they pay for all the failures and then some. But at any given moment, the majority of resources in a capitalist system are being pushed over a cliff by morons. This fascinates me. And it’s clearly the reason that humans rule the earth. We found a system to harness the power of stupid.

    From The Dilbert Blog


  4. Freakonomics Blog

    August 23, 2007 by Craig

    I’ve just discovered that the guys behind Freakonomics have a blog on the New York Times Website. And the peasants rejoiced.

    I liked this post in particular: Freakonomics v. Lolita: Can You Tell the Difference?


  5. You Are Here

    August 16, 2007 by Craig

    Today I was reading this Slashdot story about this article on tapping geothermal energy for human consumption. Good stuff.

    Of course any time there’s discussion about new energy sources, someone always brings up the unforeseen consequences argument. In this case: “wouldn’t we cool the earth’s core if we started using it’s energy, causing catastrophe?” This post says “no”:

    I’ve seen too many comments about the “effect this would have on magma under the earth if we cool it this way.” The answer to these questions is that for a long long time, we’d have virtually no effect. The scale of human activity is just to small compared to the mass of the earth -the heat source for this power generation method. Go back to school and look at the graphics that show just how thin of an area the crust occupies on the earth. http://iga.igg.cnr.it/geo/what-is-for%20IGAnew_file/image038.jpg Now imagine for yourself just how thin of an area human activity would impact.

    The poster misused “area” instead of “volume”, and he’s talking about energy impact rather than physical space, but this post did get me thinking… how much area do we actually take up? I mean us, personally, not our ecological footprint.

    So I did the math:

    • Start with 1 square metre per person. That’s roughly 3 feet to a side: a little crowded but you’re not pressed up against anyone.
    • There’s roughly 6.6 billion people on the planet.
    • 6.6 Gm2 is 6,600 km2
    • 6,600 km2 is a bit larger than P.E.I., just about the size of Delaware, and a fair bit smaller than Puerto Rico
    • If you divided Earth evenly, each person would get about 77,283 km2m2: 22,567 km2 of land and 54,716 km2 of water.
    • That works out to a plot of land about the same size as Israel or New Jersey, and (mostly saltwater) lake nearly twice the size of Lake Superior an area the size of 14 U.S. football fields, or nearly 1.5 times the base area of the Great Pyramid of Giza.
    • If you want to talk volume, each person could get a chunk of Earth 164 km3 big.
    • If you limit that volume to 2 m high (the taller of you will have to duck), each piece would be 82,000 km2 in area, which is a bit smaller than Austria.

    I call dibs on the top-left corner.

    Update:I made a big calculation mistake figuring the amount of area per person, which unfortunately lessens the entertainment value.


  6. Stupid .NET Tricks #3

    August 13, 2007 by Craig

    C# made two big language improvements over Java:

    1. If you want to override a method, you have to explicitly declare the overriding method with the “override” keyword. The compiler complains if the keyword is omitted, or if there’s no overridable method with the same signature. This goes a long way to prevent accidental overrides and broken overrides. Note that this applies for abstract methods.
    2. Inheritance of a class or inheritance (implementation) of an interface are both indicated through the same keyword/operator: “:”. This differs from Java, which uses “extends” for the former and “implements” for the latter. Using a single keyword means that you can flip the superclass or interface from one to the other without changing code in the subclasses.

    Both are great innovations, but the stupidity comes when you mix the two. The “override” keyword is only allowed when you’re subclassing; if you’re implementing an interface it is specifically disallowed. That means that you cannot, after all, easily flip the superclass to an interface (or vice versa) without changing the subclasses if the subclasses override any methods (in particular abstract methods, which are effectively the same beasts whether you’re subclassing or implementing an interface). So close…


  7. Stupid .NET Tricks #2

    August 7, 2007 by Craig

    Say you want to compare two objects (typically for sorting). How do you do it?

    You may want to consider the following:

    1. System.Collections.IComparer, an interface with a compare(Object, Object):int method. This is a direct take from Java’s Comparator interface, except with a worse name.
    2. System.Collections.Generic.IComparer<T>, a generic-friendly version of the above interface. Unlike the actual generic collections, it doesn’t inherit from the non-generic version of itself, so you can’t use one in place of the other without an adapter class.
    3. System.Collections.Generic.Comparison<T>, a delegate whose signature exactly matches the IComparer<T>’s only method. This effectively makes IComparer<T> unnecessary; you can pass around the Comparison<T> method instead of a full IComparer<T> and get the same results, except without the method naming restrictions of the interface.
    4. System.Collections.IComparable, another Java workalike. As in Java, it’s useful but misleading; it implies that there is exactly one means of comparing instances of the same class (Java calls this the “natural order” in a moralistic sort of way). IComparer is much more flexible system; IComparable is lazy and restrictive.
    5. System.Collections.Generic.IComparable<T>, another generic-friendly yet incompatible version.
    6. System.Collections.Comparer, “the default” implementation of IComparer which claims to do a case-sensitive comparison of arbitrary objects. Buh?
    7. System.Collections.CaseInsensitiveComparer, a case-insensitive version of Comparer (go figure).

    That’s 7 types to be aware of, and only one that you should really ever use.


  8. Stupid .NET Tricks #1

    August 6, 2007 by Craig

    I’m working on a .NET/C# project, which is a new environment/language for me after years of Java development. Thusfar, .NET appears to be a pretty decent language, although most of the good stuff in the language directly mimics Java. .NET did managed to fix a few of the problems with Java, but also failed to fix ones that could have been fixed without the burden of backwards compatibility.

    The reason for my post though is that .NET has introduced a few new problems that shouldn’t exist. Microsoft, with all their resources and plans for language domination, really should have known better. I’m calling these “Stupid .NET Tricks” in homage to Letterman.

    My first example is one that bugs me on a daily basis:

    1. Properties are syntactic sugar for getter and setter methods, yet you can’t pass/assign the getter, setter, nor property itself to a delegate reference, even if the appropriate method would match the delegate’s signature.

    For example:

    public delegate int ValueGetter();
    public void displayValue(ValueGetter getAValue) {
      if ( weReallyWantToDisplayTheValue() ) {
        int x = getAValue();
        display(x);
      }
    }
    
    private int aValue;
    public int AValue {
      get { return aValue; }
      set { aValue = value; }
    }
    
    public void displayAValue() {
      // This isn't allowed, even though it makes perfect sense
      // displayValue(AValue);
    
      // Instead, you have to do this:
      displayValue( delegate() { return AValue; } );
    }
    

    Note that displayValue calls a method which calls a method on the property (both methods having the exact same signature), rather than just calling the method on the property itself.

    Delegates are easily the best feature .NET has that Java doesn’t, but this oversight steals some of the thunder.