C# 4.0 Covariant Generic Interfaces + Extension Methods == Very Cool!

April 12, 2010

I ran into something at work involving a conversion routine that I had written about a year ago that takes a list of a type and converts it into a string. Today I had a new class with very similar fields that I needed to run the same coversion on. I was able to work it out in C# 3, but not quite in an ideal way. To do it the right way I’d have to be using C# 4 because if its support for covarance in interfaces, which, as it turns out, makes extension methods much more useful.

Here’s a (rather silly) example that demonstrates a situation similar to mine:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CovariantExtensionMethods
{
    public interface IMyInterface
    {
        string Value { get; set; }
    }

    public class MyClass : IMyInterface
    {
        public string Value { get; set; }
    }

    public class MyOtherClass : IMyInterface
    {
        public string Value { get; set; }
    }

    public static class MyExtensions
    {
        public static string ConvertStuff(this IEnumerable<IMyInterface> stuff)
        {
            return string.Join(", ", stuff.Select(s => s.Value));
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<MyClass> mine = new List<MyClass>
            {
                new MyClass { Value = "One" },
                new MyClass { Value = "Two" },
                new MyClass { Value = "Three" },
            };

            List<MyOtherClass> mine2 = new List<MyOtherClass>
            {
                new MyOtherClass { Value = "One" },
                new MyOtherClass { Value = "Two" },
                new MyOtherClass { Value = "Three" },
            };

            Console.WriteLine(mine.ConvertStuff());
            Console.WriteLine(mine2.ConvertStuff());
        }
    }
}

So what’s going on here? First, I have an interface, IMyInterface, that defines a single property, Value, and a class that implements that interface. Then I have an extension method, ConvertStuff, that takes an IEnumerable<IMyInterface>. In the Main method I then have a List<MyClass>, and a List<MyOtherClass>, and I call the ConvertStuff extension method on both lists – even though they are lists of different types!

In the past, this extension method would have only shown up on a variable typed as an IEnumerable<IMyInterface> (or one of its subclasses, such as List<IMyInteface>), but not on List<MyClass>, but because in .NET 4 IEnumerable now supports covariance (its definition is IEnumerable<out T>) my extension method will show up on any class that implements IEnumerable<[IMyInterface or any of its implementations]>.  This is very similar to what you’d see in Java as IEnumerable<? implements IMyInterface>, but it just happens automatically in C# 4 because the covariance is defined by the writer of the type, and not the consumer.

This makes extension methods much more versatile, and is a very welcome addition to C#.

Thanks Microsoft!

No Built-In SOAP Web Service Support on the iPhone? Seriously?

December 10, 2009

I’ve just recently started looking into doing some iPhone app development, and the first thing I noticed is how complicated-looking Objective-C is. It’s probably just that I don’t fully understand the syntax yet, and that I haven’t developed in a non-managed language in years, but to an outsider it looks overly complex.

Ignoring the language for a moment though, the thing I just can hardly believe is that the iPhone SDK does not include any built-in support for calling SOAP Web Services! Is Apple kidding? They really want me to roll my own SOAP handler? I guess I’m just to spoiled by C# – which is why I’m seriously considering using MonoTouch to do all my iPhone development. It’s managed, has a familiar programming model and syntax, and supports calling SOAP services!

How to Handle “Cannot perform this operation while dispatcher processing is suspended.” Errors in WPF

December 10, 2009

I ran in to an error today in WPF like this:

InvalidOperationException: Cannot perform this operation while dispatcher processing is suspended

After doing a little digging I found that this was happening because I was calling  Dispatcher.PushFrame inside an event handler for TabItem.IsVisibleChanged. Looking at the MSDN documentation for Dispatcher.PushFrame I found that this exception will be raised if the dispatcher processing is disabled – and one of the times that WPF disables dispatcher processing is during the layout phase (has to do with preventing nested message loops, or something). It just so happened that this event was being raised while WPF was doing layout!

The solution? Use the Dispatcher to delay my event handler until the Dispatcher is  available to handle PushFrame calls. So this:

tabItem.IsVisibleChanged += new DependencyPropertyChangedEventHandler( Tab_IsVisibleChanged );

Becomes this:

tabItem.IsVisibleChanged += (o, e) => Dispatcher.BeginInvoke( new DependencyPropertyChangedEventHandler( Tab_IsVisibleChanged ), o, e);

First step into the blogging world

November 22, 2009

I’ve never gotten into the blogging thing before, but since I’ve gotten a lot of useful information from other people’s blogs over the years, I figured I should start contributing too.

I plan to use this blog to post new and interesting things I find related to software development and technology. It’ll mostly be informational, but I may get a little editorial sometimes.

Anyway, that’s all for my “hello world” post!


Follow

Get every new post delivered to your Inbox.