Showing posts with label Orcas. Show all posts
Showing posts with label Orcas. Show all posts

Wednesday, June 20, 2007

Extension methods and Collection<T>

Visual Studio Code Analysis / FxCop says in rule CA1002 not to expose List<T> but instead something like Collection<T>.

Now List<T> has some nice features such as

List<T> List<T>.FindAll(Predicate<T> match) 

among others, not to mention

void List<T>.AddRange(IEnumerable<T> collection)

Now, we could go implementing these on our own base class and return that, or go back to C style object orientation and write a static CollectionUtilities class with methods such as

static void AddRange<T>(ICollection<T> collection, IEnumerable<T> items)

Neither of these makes me really happy.

Enter C# 3.0 extension methods:

public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> items)

{ /* implementation */ }

Now due to some compiler magic we can use this method just as it had beed implemented directly in Collection<T>... Neat!

Another interesting tidbit is that it is in fact possible to do things like

            Thing foo = null;
if (foo.IsNull())
{
Console.WriteLine("foo is null!");
}

and NOT get a NullReferenceException due to an extension method along the lines of:

        public static bool IsNull(this object value)
{
return value == null;
}

unfortunately, as they are called extension methods it's only possible for methods and not properties and such.

Thursday, September 07, 2006

Developing WCF without Orcas CTP

For various reasons I installed the .NET 3.0 RC1 Runtime/SDK as soon as they were available. This meant that I didn't have a CTP of Orcas to go with it. As I currently don't have any WPF stuff to do I figured I'd manage just as fine without it.

However, when I started a new project using WCF it got interesting, I could build already made WCF projects, but System.ServiceModel (and System.Runtime.Serialization for that matter) was nowhere to be found in the Add reference... dialog.

As I also do fiddle around with msbuild stuff I figured that I could work around this quite easily by firing up the project xml file (right-click the project, choose Unload project, right-click the unloaded project, choose Edit .csproj, Edit away..., then right-click project, Reload project)

and add the missing reference to the project by hand

<Reference Include="System.ServiceModel" />

Still, I thought it was kinda funny that the workaround was needed.


EDIT: This is not an issue anymore since Orcas CTP for RC1 has been released.