1. .NET 3.5: Properties and Delegates: A New Solution to an Old Problem

    November 20, 2007 by Craig

    A while ago I ranted about how .NET properties didn’t play nice with delegates. The gist was that, if you had a property and a method which took a delegate of the appropriate type, you had to write your own new delegate method, even though the property’s getter and setter would ordinarily qualify. Here’s an example:

    public class Foo {
      public String Bar { get; set; }
    }
    
    public delegate String GetString();
    public void display(GetString getString){
      Console.WriteLine(getString());
    }
    
    public void performOnAValue(Action <String> action){
      action("A Value");
    }
    
    Foo foo = new Foo { Bar = "bar" };
    // You can't do this, because .NET doesn't recognize 
    // Foo.Bar.get() and Foo.Bar.set() as valid methods
    // performOnAValue(foo.Bar);    // foo.Bar.set() satisfies Action<String>
    // display(Foo.Bar);            // foo.Bar.get() satisfies GetString
    
    // Instead you have to do this in .NET 2.0:
    performOnAValue(delegate(String value) {
      foo.Bar = value;
    });
    display(delegate() {
      return foo.Bar;
    });
    

    Unfortunately, .NET 3.5 doesn’t fix this. However, it does give us enough new features that we can fake it. Consider this:

    public static class Getter {
      public static T get<T>(this T target) {
        return target;
      }
    }
    

    This extension method adds a get() method to every type. That means that we can do this:

    display(foo.Bar.get<String>);
    

    Even though Getter.get() doesn’t satisfy the GetString() signature (since it takes a <T>), .NET is smart enough to figure out that if you call it as an extension it will work.

    The bad news is that you do have to specify the type of the object as the generic type parameter of get(). You could write a non-generic version that gets and returns an Object, but that leads to the potential for InvalidCastExceptions. The good news is that if you do use the wrong generic type parameter (let’s say foo.Bar.get<int>), the compiler will complain (albeit with a confusing error message).

    More bad news: there’s no equivalent extension method for the setter. Without resorting to reflection, there’s no way (that I am aware of) to programmatically access an arbitrary property of an object from within a method. However, lambda expressions make the pain of writing a delegate a little easier to bear:

    performOnAValue(value => foo.Bar = value);
    

    You can also do the same for the getter, if you use an empty input parameter list and an inferred return keyword:

    display( () => foo.Bar );
    

    I’m not sure whether the lambda or the extension method getter is less ugly.

    With these options, I’d say that the Stupid .NET Trick of properties and delegates is about 75% solved. The syntax is not as clean as it could be, but it’s a big step forward… possibly enough to make properties worth it again.


  2. .NET 3.5: Lambda Expressions, Type Inference, and Anonymous Methods

    by Craig

    As of v2.0, .NET already had support for first-class function types through delegates. v3.5 adds in a new concise syntax for creating short delegates.

    public void performOnAllMembers(Action<Foo> action) {
      foreach( Foo foo in datastructure ) {
        action(foo);
      }
    }
    
    // Old syntax
    performOnAllMembers(delegate(Foo foo) {
      foo.bar();
    });
    
    // New Lambda Syntax
    performOnAllMembers( foo => foo.bar() );
    

    Besides shortening “delegate” to “=>”, most of the keyboard savings here comes from type inference; you no longer have to declare that “foo” is a “Foo” since performOnAllMembers() already declares that it needs an Action to perform on a Foo. Note that this is just an assumption in the source code; everything is still strongly typed and the compiler will complain if you pass anything that’s not compatible with “Foo”.

    Too Much Type Hiding?

    While the source code does look cleaner, I generally believe explicitness is a virtue, and type inference works against that. If you don’t happen to have the method signature/documentation/source code for performOnAllMembers() handy, then you might be left wondering exactly of what type foo is and what it’s capable of. That means that you have to interrupt your flow of reading the source to go and look up the performOnAllMembers() contract; this interruption can only hurt your ability to understand what’s going on. The relaxed-typing proponents claim that this isn’t a big deal; I haven’t had a lot of experience with non-strong typing so I’m cautiously withholding judgment.

    Anonymous Types

    .NET 3.5 takes type inference one step further with anonymous types. These are similar to the Java anonymous inner types, except with a better syntax:

    var myReference = new { Foo = "foo", Bar = 1 };
    

    myReference points a instance with a strong type, and behaves as such; the type name is just hidden. Combined with the new property initialization syntax, .NET comes very close to having tuples. However, there’s a big catch with anonymous types: they’re only valid as local variables. That means you can’t pass them as parameters, get them as return values, or use them as generic type parameters (which means they can’t be stored in generic collections except as Objects). Moreover it doesn’t appear that they can ever be given methods; they’re basically local, dynamically generated structs (and I mean C dumb structs, not C# wannabe-classes structs).

    There’s also something to do with lambda expressions called “Expression Trees”. I haven’t investigated this in detail yet, but it looks promising. Scott Guthrie has more to say on it. I’ll probably post more once I read up on it.


  3. .NET 3.5: Extension Methods

    by Craig

    Extension methods are static methods that, through the magic of the compiler and Visual Studio’s IntelliSense, can be made to appear as if they’re actually members of a particular type. The key is that the target type can be any type, including the standard .NET types. Thus, if you want to add features to a 3rd-party class, you don’t have to resort to Booch utilities.

    public static class MyExtension {
      public static String prefixWith(this String target, String prefix ){
        return prefix + target;
      }
    }
    
    String result = "foo".prefixWith("bar");
    

    This is a decent feature, although I have two concerns:

    1. There’s potential for developer confusion, especially with developers reading unfamiliar code. “prefixWith()” isn’t a standard known method of String so you’re going to be thrown for a bit of a loop when you see it. Ordinary static methods at least have a big class name attached to them so it’s obvious when you’re using nonstandard code.
    2. I’m yet not sure how extension methods avoid name collision, but it’s bound to become an issue. All you have to do to attach an extension method on potentially every type in the system is to import the namespace of a class that defines the extension method. That can get out of hand quickly.

    Lastly, there’s one cool feature with extension methods: since they’re just syntactic sugar for a static method, they don’t require an actual instance in order to “use them on a reference”. So I could have:

    public static class MyExtension {
      public static bool isNull(Object o ){
        return o == null;
      }
    }
    
    String foo = null;
    return foo.isNull();
    

    By the way, that sound you hear is the Ruby enthusiasts snickering.


  4. .NET 3.5: Property Enhancements

    by Craig

    .NET 3.5 adds a few syntax enhancements regarding properties.

    Automatic Properties

    You no longer have to declare the private field, getter, or setter methods when creating a property; the compiler will handle it for you.

    class Foo {
      public String Bar { get; set; }
    }
    

    When I first started learning .NET, I actually thought that this feature had already been built into the language, and was surprised when I found I had to write my own (repetitive) property code. Automatic properties finally alleviates that.

    Note: You can only declare read-write automatic properties. If you want a read-only or a write-only property, you have to do the legwork yourself. Note that access modifiers can still be used, so you could have a public property with a private setter — but that’s not the same thing as read-only.

    Property Initialization

    There’s a new syntax for assigning values to properties during object creation:

    Foo foo = new Foo { Bar = "bar", Baz = 1 };
    

    If you have mutable objects that don’t have any constructor logic, then this enhancement helps reduce a lot of verbose dereferencing code with a nice constructor-like syntax. Generally I prefer my classes immutable and constructor-populated, but there’s lots of times where that’s not feasible.

    This makes two worthwhile enhancements to properties. Unfortunately, by themselves they wouldn’t do me much good: I intentionally avoid using properties (in favor of explicit getter/setter methods) because properties are completely unusable with delegates. However, some of the other new .NET features help to compensate for this, so I’m still counting these features as a win.


  5. .NET 3.5

    by Craig

    The latest version of the .NET Framework, v3.5, was released yesterday. As usual, there’s a bunch of new libraries and Visual Studio enhancements (particularly when it comes to web applications). Those are nice, but what really caught my attention was the core language enhancements, which are pretty significant.

    Scott Guthrie is one of the head honchos in that particular neighborhood of Microsoft. His blog talks about the new language features in pretty good detail, so I’m going to keep the descriptions to a minimum and focus more on commentary.

    This post got pretty long so I decided to split it up:


  6. Wikipedia Tourism 2

    by Craig

    The Phantom of the Opera Sequel

    On February 16, 2007 Andrew Lloyd Webber announced that he is working on [The Phantom of the Opera’s] sequel. The sequel is called The Phantom of Manhattan and is adapted from the novel of the same name, published in 1999, written by Frederick Forsyth.

    However, according to a report published in the Daily Mail newspaper, a bizarre mishap has delayed the sequel; Lloyd Webber’s cat, Otto, a rare-breed Turkish Van, clambered onto the digital Clavinova piano and managed to delete the entire score for Phantom of Manhattan. Lloyd Webber was unable to recover any of it from the instrument.

    First the Library of Alexandria burns, and now this.


  7. Stupid .NET Tricks #9

    November 19, 2007 by Craig

    The HTMLSelect.Name is always the same as its ID/UniqueID properties. The documentation states:

    Use the Name property to determine the unique identifier name for an HtmlSelect control. In this implementation, the get accessor returns the value of the Control.UniqueID property. However, the set accessor does not assign a value to this property.

    The set accessor does not assign a value to this property because the Name property must have the same value as the Control.UniqueID property for the HtmlSelect control to work properly.

    Thus, you can’t output an HTML <select> element that has different values for the “name” property and “id” attributes… unless you re-implement the code to do so yourself.

    This isn’t the case for most other controls in the System.Web.UI.HtmlControls namespace. There’s no stated reason why the restriction is so necessary either. You have to really wonder WTF is going on over at Microsoft for a team to code in a seemingly arbitrary restriction and document it but not fix the problem in the first place.


  8. Stupid .NET Tricks #8

    November 12, 2007 by Craig

    ASP.NET, in its grand paternal wisdom, replaces the “id” attribute on any server-side-enabled control with a dynamically generated (and thus guaranteed to be unique) value. So, when you write this:

    <div id="foo"></div>
    

    …what you actually get is something like this:

    <div id="ctl00$page_content_replace$ctl00$foo"></div>
    

    …thus dashing any hope you had of writing proper DOM-aware content (such as JavaScript and CSS).

    Update: Oh yeah, and it changes the “name” attribute of input fields too, thus ensuring that your form parameters and query strings are utterly nasty.

    Update 2: JonEHolland writes (below):

    Use the ClientID attribute to specify ID once the control is rendered.

    IE:

    <div ClientId=”someId” id=”ServerSideId” runat=”server”></div>

    Renders:

    <div id=”someId” ></div>

    I tried setting ClientId (and ClientID and clientid) and it didn’t help for several reasons:

    1. ASP.NET did not actually copy my server-side ClientID attribute to the client-side ID attribute as JonEHolland stated. The id attribute was the same generated string.
    2. It did, however, pass the same ClientID attribute and value on to the client (basically it left the unrecognized attribute alone, as it should). That could be somewhat useful, especially if you’re generating arbitrary XML. However, it doesn’t solve the core problem of the munged IDs; CSS/JavaScript won’t recognize ClientID without a lot of extra hacking.
    3. ClientID isn’t valid in the XHTML 1.0 Strict DTD, so Visual Studio complains about it. If you use any uppercase letters (such as ClientID) it actually generates an error; if you stick to lowercase (clientid) it lets you off with a warning.
    4. On the C# side: the ClientID property of Control is read-only and thus not changeable to anything. (ID is changeable but the change is ignored/overwritten by the time the control is rendered — at least as far as I’ve probed. Perhaps there’s a point in the control lifecycle where you can actually set it? Even if there is it appears to be too dicey to be worthwhile.)
    5. The ClientID property does provide me with the ID that ASP.NET has chosen for the element. If I wanted to generate CSS or JavaScript that used the element’s ID, I could use this property to discover the ID that would be used. But that’s horribly ugly and restrictive.

    Sorry, JonEHolland; it doesn’t look like this works. If I’ve missed something let me know, but it appears that you’re incorrect.

    Update 3: JonEHolland points to this blog post by Rick Strahl which describes how to bypass the ID munging by overriding the UniqueID and ClientID properties. That’s better than nothing, and just fine if you’re developing your own controls, but it still doesn’t solve the problem for the standard ASP.NET controls (in System.Web.UI.WebControls and System.Web.UI.HtmlControls); you’d have to create a whole bunch of new classes.


  9. Wikipedia Tourism

    November 8, 2007 by Craig

    Just for the heck of it. From History of Aqua regia (one of the few substances that can dissolve gold):

    When Germany invaded Denmark in World War II, the Hungarian chemist George de Hevesy dissolved the gold Nobel Prizes of Max von Laue and James Franck into aqua regia to prevent the Nazis from stealing them. He placed the resulting solution on a shelf in his laboratory at the Niels Bohr Institute. It was subsequently ignored by the Nazis who thought the jar—one of perhaps hundreds on the shelving—contained common chemicals. After the war, de Hevesy returned to find the solution undisturbed and precipitated the gold out of the acid. The gold was returned to the Royal Swedish Academy of Sciences and the Nobel Foundation presented new medals to Laue and Franck.