Copenhagen C# talk videos now up

The videos from my one day talk about C# in Copenhagen are now on the MSDN community site. There are eight sessions, varying between about 25 minutes and 50 minutes in length. I haven’t had time to watch them yet, but when I do I’ll submit brief summaries so you can quickly get to the bits you’re most interested in. (As far as I’m aware, they’re only available via Silverlight, which I realise isn’t going to be convenient for everyone.)

Feedback is very welcome.

November 19th: London .NET User Group, Push LINQ!

On November 19th, I’ll be speaking at the London .NET User Group about Push LINQ. I was quite pleasantly surprised by being able to explain it to some extent in Copenhagen, and this evening will be entirely about Push LINQ, so I’ll be able to go into a lot more detail. Skills Matter will be hosting the event (near Farringdon station). It starts at 6.30pm, and registration is now open.

Should be fun. Please come and heckle.

How much do you care about blog tags?

Occasionally I feel that my collection of tags is somewhat lacking. For instance, I’ve been thinking of adding “language design” and “public speaking” tags – and then going through previous posts and retagging where appropriate.

However, I’d rather not do this if no-one actually uses tags in the first place. I know that I find the tags on Eric Lippert’s blog incredibly handy when I’m going back to look for a particular article, but I suspect that’s mostly because Eric’s blog is so quotable in the first place.

Would it help any of you for me to be more comprehensive and historically accurate with my tags? If so, I’ll go ahead… otherwise I’ll waste some more time on Stack Overflow :)

Jaffa bugs

Currently I’m working on a problem found by one of our testers. Unfortunately, it’s hard to reproduce. Inspired by the fact that yesterday our micro-kitchen had jaffa cakes in, I propose that if we’re going to be frustrated by bugs like this, we might as well at least mock them.

I propose that we call them jaffa bugs, and will work hard to promote this jargon until it takes over the world. Insert evil laugh here.

(Just in case the etymology here isn’t clear, see the Wikipedia “Only Fools and Horses” entry.)

.NET 4.0’s game-changing feature? Maybe contracts…

Update: As Chris Nahr pointed out, there’s a blog post by Melitta Andersen of the BCL team explaining this in more detail.

Obviously I’ve been looking at the proposed C# 4.0 features pretty carefully, and I promise I’ll blog more about them at some later date – but yesterday I watched a PDC video which blew me away.

As ever, a new version of .NET means more than just language changes – Justin van Patten has written an excellent blog post about what to expect in the core of thee framework. There are nice things in there – tuples and BigInteger, for example – but it was code contracts that really caught my eye.

Remember Spec#? Well, as far as I can tell the team behind it realised that people don’t really want to have to learn a new language – but if the goodness of Design By Contract can be put into a library, then everyone can use it. Enter CodeContracts…

Actual examples are relatively few and far between at the moment, but the basic idea is that you write your contracts at the start of methods – not in attributes, presumably because that’s too limiting in terms of what you can express – and then a post-build tool will “understand” those contracts, find potential issues, and do a bit of code-rewriting where appropriate (e.g. to move the post-condition testing to the end points of the method). Object invariants can also be expressed as separate methods.

Rather than guess at the syntax in this blog post I highly recommend you watch the PDC 2008 video on both this and Pex (an intelligent code explorer and test generator). The teams have clearly thought through a lot of significant issues:

  • Contracts can be enforced at runtime, or stripped out for release builds. (I’ll be interested to see whether I can keep the pre-condition checks in the release build, just removing invariants and post-conditions etc.)
  • If you’re stripping out the contracts, you can still have them in a separate assembly – so if you supply a library to someone, they can still have all the Design by Contract goodness available, and see where they’re potentially violating your preconditions
  • Contracts will be automatically documented in the generated XML documentation file (although this has yet to be implemented, I believe)
  • Interfaces can be associated with contract classes where the contracts are expressed. (They couldn’t be in the interface, as they require method bodies.)
  • Pex will be able to generate tests in MS Test, NUnit and MbUnit. (Hooray! This got a massive cheer at PDC.)

Now I should point out that I haven’t tried any of this – I’ve just watched a video which was very slick and obviously used a well-tested scenario. If this genuinely works, however, I think it could change the way mainstream developers approach coding just as LINQ is changing the way we see data. (Obviously there’s nothing fundamentally new about DbC – but there’s a difference between it existing and it being mainstream.)

I’m really, really excited about this :) Definitely time to boot up the VPC image when I get a moment…

Returning from Copenhagen

I’m currently sitting in Copenhagen airport, with two hours to wait before my flight boards. It’s been a tiring day – my feet in particular are aching somewhat, and my throat is quite sort – but I’ve thoroughly enjoyed it. We started the actual talk at about 10am and finished at 4pm, with three breaks totalling about an hour – so I was speaking for five hours. You might have thought that with all that time, it would be easy to go into a lot of detail about C# 2 and 3, but there’s really too much to cover everything. Topics I remember talking about:

  • Generics (assuming everyone knew the basics – talked about static members, constraints)
  • Iterator blocks
  • Anonymous methods
  • Automatic properties
  • Anonymous types
  • Object/collection initializers (really briefly)
  • Lambda expressions
  • Extension methods
  • Query translation (at a very broad level)
  • The basics of LINQ to Objects, including streaming/buffering and deferred/immediate execution
  • Push LINQ and Protocol Buffers
  • C# 4
  • What I’d like to see in C# 5

The whole session was recorded – I’ll post a link when it’s ready, along with slides and code – if you really want to sit through 5 hours of me talking :)

Anyway, I’ve had a great time, and massive thanks to Brian Rasmussen for organising it and letting me stay in his beautiful home, as well as to Microsoft for hosting the event and Google for giving me the go-ahead to do it.

Next stop: London .NET User Group on November 19th, talking about Push LINQ (in more detail).

C# 4.0: dynamic ?

I’ve not played with the VS2010 CTP much yet, and I’ve only looked briefly at the documentation and blogs about the new C# 4.0 dynamic type, but a thought occurred to me: why not have the option of making it generic as a way of saying “I will dynamically support this set of operations”?

As an example of what I mean, suppose you have an interface IMessageRouter like this:

public interface IMessageRouter
{
    void Send(string message, string destination);
}

(This is an arbitrary example, by the way. The idea isn’t specifically more suitable for message routing than anything else.)

I may have various implementations, written in various languages (or COM) which support the Send method with those parameters. Some of those implementations actually implement IMessageRouter but some don’t. I’d like to be able to do the following:

dynamic<IMessageRouter> router = GetRouter();

// This is fine (but still invoked dynamically)
router.Send(“message”, “skeet@pobox.com”);
// Compilation error: no such overload
router.Send(“message”, “skeet@pobox.com”, 20);

Intellisense would work, and we’d still have some of the benefits of static typing but without the implementations having to know about your interface. Of course, it would be quite easy to create an implementation of the interface which did exactly this – but now imagine that instead of IMessageRouter we had MessageRouter – a concrete class. In this case the compiler would still restrict the caller to the public API of the class, but it wouldn’t have to be the real class. No checking would be performed by the compiler that your dynamic type actually supported the operations – given that we’re talking about dynamic invocation, that would be impossible to do. It would instead be an “opt-in” restriction the client places on themselves. It could also potentially help with performance – if the binding involved realised that the actual type of the dynamic object natively implemented the interface or was/derived from the class, then no real dynamic calls need be made; just route all directly.

This may all sound a bit fuzzy – I’m extremely sleepy, to be honest – but I think it’s a potentially interesting idea. Thoughts?

Update

Apparently this post wasn’t as clear as it might be. I’m quite happy to keep the currently proposed dynamic type idea as well – I’d like this as an additional way of using dynamic objects.

What other Enumerable extension methods would you like to see?

A few questions on Stack Overflow have suggested to me that there might be some bits missing from LINQ to Objects. There’s the idea of a “zip” operator, which pairs up two sequences, for instance. Or the ability to apply the set operators with projections, e.g. DistinctBy, IntersectBy etc (mirroring OrderBy). They’re easy to implement, but it would be nice to get a list of what people would like to see.

So, what’s missing?

Mapping from a type to an instance of that type

A question came up on Stack Overflow yesterday which I’ve had to deal with myself before now. There are times when it’s helpful to have one value per type, and that value should be an instance of that type. To express it in pseudo-code, you want an IDictionary<typeof(T), T> except with T varying across all possible types. Indeed, this came up in Protocol Buffers at least once, I believe.

.NET generics don’t have any way of expressing this, and you end up with boxing and a cast. I decided to encapsulate this (in MiscUtil of course, although it’s not in a released version yet) so that I could have all the nastiness in a single place, leaving the client code relatively clean. The client code makes calls to generic methods which either take an instance of the type argument or return one. It’s a really simple class, but a potentially useful one:

/// <summary>
/// Map from types to instances of those types, e.g. int to 10 and
/// string to “hi” within the same dictionary. This cannot be done
/// without casting (and boxing for value types) as .NET cannot
/// represent this relationship with generics in their current form.
/// This class encapsulates the nastiness in a single place.
/// </summary>
public class DictionaryByType
{
    private readonly IDictionary<Type, object> dictionary = new Dictionary<Type, object>();

    /// <summary>
    /// Maps the specified type argument to the given value. If
    /// the type argument already has a value within the dictionary,
    /// ArgumentException is thrown.
    /// </summary>
    public void Add<T>(T value)
    {
        dictionary.Add(typeof(T), value);
    }

    /// <summary>
    /// Maps the specified type argument to the given value. If
    /// the type argument already has a value within the dictionary, it
    /// is overwritten.
    /// </summary>
    public void Put<T>(T value)
    {
        dictionary[typeof(T)] = value;
    }

    /// <summary>
    /// Attempts to fetch a value from the dictionary, throwing a
    /// KeyNotFoundException if the specified type argument has no
    /// entry in the dictionary.
    /// </summary>
    public T Get<T>()
    {
        return (T) dictionary[typeof(T)];
    }

    /// <summary>
    /// Attempts to fetch a value from the dictionary, returning false and
    /// setting the output parameter to the default value for T if it
    /// fails, or returning true and setting the output parameter to the
    /// fetched value if it succeeds.
    /// </summary>
    public bool TryGet<T>(out T value)
    {
        object tmp;
        if (dictionary.TryGetValue(typeof(T), out tmp))
        {
            value = (T) tmp;
            return true;
        }
        value = default(T);
        return false;
    }
}

It doesn’t implement any of the common collection interfaces, because it would have to do so in a way which exposed the nastiness. I’m tempted to make it implement IEnumerable<KeyValuePair<Type, object>> but even that’s somewhat unpleasant and unlikely to be useful. Easy to add at a later date if necessary.

(I know the XML documentation leaves something to be desired. One day I’ll learn how to really do it properly – currently I fumble around if I’m trying to refer to other types etc within the docs.)