C#

Giving C# a Times method

Want to be able to write code like “5.Times” but you can’t use a language like Ruby? You can do this in C# with some extension method magic. public static void Times(this int numberOfTimes, Action action) { for (var number = 0; number < numberOfTimes; number++) { action(); } } Now you can write code like: 5.Times(() => Console.WriteLine("Hello")); Sometimes however you want to know the index of the invocation of the lambda. This can be done with: public static void Times(this int numberOfTimes, Action<int> action) { ...

posted @ Saturday, August 14, 2010 1:36 PM | Feedback (0)

What’s good in .NET?

Lest my previous post is interpreted as my not liking the .NET platform, here’s a collection of things that are great (and which you will have to prise from my cold dead fingers). Lambdas, Extension Methods and the Enumerable and Queryable classes. How did we ever live without them? ReSharper. Visual Studio is merely my ReSharper hosting environment. Please JetBrains, write a .NET IDE. TestDriven.NET. So much faster than anything else out there for running unit tests. Does one thing, does it amazingly well. Gallio and MbUnit....

posted @ Sunday, December 13, 2009 3:45 PM | Feedback (0)

In which I rant about how Microsoft views developers

Disclaimer: Microsoft is a large and heterogeneous company and these comments will not necessarily apply to all of the organisation. I’ve just read a blog post by a Microsoft Software Engineer that represents what I believe is the fundamental problem with how Microsoft views the developers who use their tools and APIs. Here are the two key quotes: “We sit around the table designing APIs, and for the most part unless we have time to actually think through the extensibility/usage scenarios and ensure they’re safe or at least make some sense,...

posted @ Sunday, December 13, 2009 2:53 PM | Feedback (2)

I want non-nullable reference types

C# 2.0 introduced Nullable which gives us the ability to have nullable value types. This is handy and makes a number of scenarios easier (particularly database interaction in my experience). It’s very much in the category “nice to have”, useful but in most cases not essential. What I want is the inverse, reference types that cannot be null. NullReferenceException is one of the least helpful exceptions you can expect to encounter. It carries very little information, generally leaving you with “something broke in there somewhere and its all your fault”. In almost all cases you get this exception because...

posted @ Tuesday, December 08, 2009 9:31 PM | Feedback (2)

‘as’ is no safer than cast without a null check

I’ve recently encountered code which looks something like: var someInstance = someParameter as ISomething; someInstance.DoSomething();   The problem with this code is that it is wide open for a highly unhelpful NullReferenceException. If someParameter cannot be cast to ISomething the as operator will return null. But this code doesn’t check if someInstance is null. It makes the assumption that someParameter may be case to ISomething, even though in practice this assumption may not hold. There are two solutions to this. You may replace the use of the as operator with an explicit cast. This will throw an InvalidCastException if the cast cannot be...

posted @ Tuesday, November 03, 2009 3:44 PM | Feedback (2)

Chain of responsibility using LINQ Extension methods

I recently had reason to implement a simple chain of responsibility in order to simplify some logic. Rather than a large number of sequential if statements to implement a sequence of conditional exclusive actions I used this structure to simplify the logic. The basis of the implementation is a field that is a collection of delegates. The delegate take parameters as needed to determine if an action is applicable and also to implement the action. It also returns bool. For example: private static readonly ICollection<Func<TestObject, bool>> _chain = new List<Func<TestObject, bool>> { ...

posted @ Friday, July 03, 2009 11:45 PM | Feedback (0)

NDepend tip: Exclude that which the code generator hath wrought

I’ve been running NDepend over some of my projects recently and have noticed a tendency for it to pick up on things in code generated by Visual Studio (which admittedly is of highly variable quality). I’m not going to write my own version of the generated code but I would like to clear out the noise. You can do so by editing the CQL and adding something like: AND !FullNameLike ".*Properties.Resources.*" This criteria excludes anything that matches the common pattern of the standard resource files produced by Visual Studio. You can...

posted @ Saturday, June 20, 2009 10:14 PM | Feedback (0)

Today’s nitpicking of the .NET BCL

From the IDisposable  Dispose method documentation: If an object's Dispose method is called more than once, the object must ignore all calls after the first one. The object must not throw an exception if its Dispose method is called multiple times. But what happens in you call Dispose twice on ReaderWriterLockSlim? A shiny ObjectDisposedException. Oops. For the record I discovered this while unit testing the multiple dispose behaviour of one of my own classes not in production code. Annoyingly it makes testing the disposed behaviour of my class difficult as my tests will...

posted @ Thursday, March 12, 2009 7:35 PM | Feedback (1)

Type system limitations that are annoying me today

Every now and they I run into something that makes me wish C# was more dynamic. Today’s example is playing with delegates. For instance the following works: public void Test() { Func<object> blah = Blah; blah(); } public string Blah() { return string.Empty; } This is valid because the return type of the method is always more restrictive than that of the delegate (that is it is covariant). Unfortunately this breaks down with delegate assignment: public void Test() { Func<string> blah1 = Blah; Func<object> blah2 = blah1; blah2(); } public string...

posted @ Sunday, March 01, 2009 6:22 PM | Feedback (1)

Small Code Improvements Part 3: Using Enumerable.Select to map collections

The Enumerable.Select method is used in LINQ to perform query magic. It may also be used in scenarios where you wish to transform a collection. The most common use to which I put this is in mapping between domain and message objects. The system I'm currently working with maintains a clear distinction between the wire format and the domain. This requires that there be a mapping between the formats. This is performed by a series of mapper classes that handle mapping between different message and domain types. This is composable, for instance an address mapper may be injected into...

posted @ Thursday, January 15, 2009 11:31 PM | Feedback (0)

.NET 3.5 SP1 doesn't seem ready for release

.NET 3.5 SP1 has only just been released any I've already seen three distinct reports that it's introduced bugs that break applications. See here and here for examples, and at least one vendor who's update list I'm on has sent a warning email to notify people .NET 3.5 SP1 breaks their product. Fortunately I've only installed it on my home system which I don't use for anything but personal development. Given the nature of .NET 3.5 (such as the shared runtime with .NET 2.0/3.0) this has the potential to break applications running on earlier .NET versions. Solid testing before...

posted @ Thursday, August 14, 2008 10:29 AM | Feedback (0)

Alternatives to switch statements

It's previously been established that I have a deep and abiding distaste for switch statements. This post will discuss alternate mechanisms that display superior maintainability and flexibility.Let's take a trivial example switch statement:var action = Console.ReadLine(); switch (action) { case "blah": Console.WriteLine("All a bit blah."); break; case "stuff": Console.WriteLine("Stuff happened."); break; case "other stuff": Console.WriteLine("Other stuff happened."); ...

posted @ Sunday, March 23, 2008 1:36 PM | Feedback (0)

Applying logic to disparate items in C# 3.0

Yesterday's example showed how to use anonymous methods to apply logic to disparate items. This example was written in C# 2.0. Today I'll demonstrate how to convert this to C# 3.0 and use lambda expressions instead of anonymous methods.I'll start with the TestItem class, which can be significantly simplified. The new class is:public class TestItem { public int FirstValue { get; set; } public int SecondValue { get; set; } } This converts the properties to automatic properties and loses the constructors as I'll be using the new object initialisers functionality...

posted @ Saturday, March 22, 2008 5:17 AM | Feedback (0)

Applying logic to disparate items with anonymous methods

My previous post suggested that it is possible to apply the same logic to elements that are disparate, that is do not have a common base class or interface that is relevant to the operation. This post describes a method of doing this using anonymous methods. I will use a simple example of summing values, but the principal is applicable generally, and is not specific to looping.Take for instance the following code:List<int> integerList = new List<int>();for (int initialValue = 1; initialValue <= 5; initialValue++){ integerList.Add(initialValue);}int sum = 0;foreach (int value in integerList){ sum...

posted @ Friday, March 21, 2008 8:30 AM | Feedback (0)

No Resharper with C# 3.0 support makes Colin go something something...

I've been doing some development with the new C# 3.0 features which means I'm faced with two unpleasant alternatives: Disable ReSharper and deal with the low level stress of a sub-optimal development environment. Keep ReSharper enabled and have to deal with the autocomplete issues and code analysis failures when dealing with C# 3.0 features. Neither alternative is particularly pleasant. I'm turning into a forum junkie, checking constantly for signs that an EAP version has been released. It's not pretty. 

posted @ Thursday, January 24, 2008 2:21 AM | Feedback (0)

Switch statements should only be available on prescription

One of the most consistent features I see in codebases that are in need of refactoring are developers doing terrible, terrible things with switch statements. They start out as small, manageable things but over time a series of expedient changes leaves you with a 1000 line long abomination full of duplicate code, hidden dependencies and unresolvable bugs.   One of the problems is that in most cases it seems so much more efficient to use a switch statement than the alternatives which generally need at least a couple of new classes. For a few cases this may be true but as the...

posted @ Friday, January 04, 2008 2:17 AM | Feedback (0)