Yup you heard it right, SuperFun Town has been added to Hi5 and is currently one of the featured games in the revamped Games page. Start playing today!
Yup you heard it right, SuperFun Town has been added to Hi5 and is currently one of the featured games in the revamped Games page. Start playing today!
Stumbled across ic#code’s free ebook ‘The fine art of commenting’ this morning, it’s from 2002 but everything still applies, you can download it here.
The book covers commenting in general and not just C#, but in relation to C# here’s the list of the predefined xml tags you can use in comments (something I have to search every time..):
| <c> | Marks a part of a comment to be formatted as code |
| <code> | As above, but multiline |
| <example> | For embedding examples in comments, usually uses <c> |
| <exception>* | Documents an Exception class |
| <include>* | Includes documentation from other files |
| <list> | A list of <term>s defined by <description>s |
| <para> | Structures text blocks, e.g. in a <remark> |
| <param>* | Describes a method parameter |
| <paramref>* | Indicates that a word is used as reference to a parameter |
| <permission>* | Gives the access permissions to a member |
| <remarks> | For overview of what a given class or other type does |
| <returns> | Description of the return value |
| <see>* | Refers to a member or field available |
| <seealso>* | As above, but displays a ‘See also’ section |
| <summary> | A summary of the object |
| <value> | Describes a property |
* validated by the C# compiler
Having spent quite a bit of time coding in F# recently I have thoroughly enjoyed the experience of coding in a functional style and come to really like the fact you can do so much with so little code.
One of the counter-claims against F# has always been the concerns over performance in the most performance critical applications, and with that in mind I decided to do a little experiment of my own using C# (LINQ & PLINQ) and F# to generate all the prime numbers under a given max value.
The LINQ and PLINQ methods in C# look something like this:
private static void DoCalcSequentially(int max)
{
var numbers = Enumerable.Range(3, max-3);
var query =
numbers
.Where(n => Enumerable.Range(2, (int)Math.Sqrt(n))
.All(i => n % i != 0));
query.ToArray();
}
private static void DoCalcInParallel(int max)
{
var numbers = Enumerable.Range(3, max-3);
var parallelQuery =
numbers
.AsParallel()
.Where(n => Enumerable.Range(2, (int)Math.Sqrt(n))
.All(i => n % i != 0));
parallelQuery.ToArray();
}
The F# version on the other hand uses the fairly optimized algorithm I had been using in most of my project euler solutions:
let mutable primeNumbers = [2]
// generate all prime numbers under <= this max
let getPrimes max =
// only check the prime numbers which are <= the square root of the number n
let hasDivisor n =
primeNumbers
|> Seq.takeWhile (fun n' -> n' <= int(sqrt(double(n))))
|> Seq.exists (fun n' -> n % n' = 0)
// only check odd numbers <= max
let potentialPrimes = Seq.unfold (fun n -> if n > max then None else Some(n, n+2)) 3
// populate the prime numbers list
for n in potentialPrimes do if not(hasDivisor n) then primeNumbers <- primeNumbers @ [n]
primeNumbers
Here’s the average execution time in milliseconds for each of these methods over 3 runs for max = 1000, 10000, 100000, 1000000:

Have to admit this doesn’t make for a very comfortable reading…on average the F# version, despite being optimized, runs over 3 – 6 times as long as the standard LINQ version! The PLINQ version on the other hand, is slower in comparison to the standard LINQ version when the set of data is small as the overhead of partitioning, collating and coordinating the extra threads actually slows things down, but on a larger dataset the benefit of parallel processing starts to shine through.
Thanks for Jaen’s comment, the cause for the F# version of the code to be much slower is because of this line:
primeNumbers <- primeNumbers @ [n]
because a new list is constructed every time and all elements from the previous list copied over.
Unfortunately, there’s no way to add an element to an existing List or Array in F# without getting a new list back (at least I don’t know of a way to do this), so to get around this performance handicap the easiest way is to make the prime numbers list a generic List instead (yup, luckily you are free to use CLR types in F#):
open System.Collections.Generic
// initialize the prime numbers list with 2
let mutable primeNumbers = new List<int>()
primeNumbers.Add(2)
// as before
...
// populate the prime numbers list
for n in potentialPrimes do if not(hasDivisor n) then primeNumbers.Add(n)
primeNumbers
With this change, the performance of the F# code is now comparable to that of the standard LINQ version.
Ever tried to use IEnumerable<T>.Sum on an array of unsigned long integers? Well, you can’t, because the Sum method has not been implemented for ulong or ulong?, so to fill in the gap here’s the extension methods you need using more or less the same code as the existing Sum methods:
[CheckParameters]
public static ulong Sum([NotNull] this IEnumerable<ulong> source)
{
var sum = 0UL;
foreach (var number in source)
{
sum += number;
}
return sum;
}
[CheckParameters]
public static ulong? Sum([NotNull] this IEnumerable<ulong?> source)
{
var sum = 0UL;
foreach (var nullable in source)
{
if (nullable.HasValue)
{
sum += nullable.GetValueOrDefault();
}
}
return sum;
}
[CheckParameters]
public static ulong Sum<T>([NotNull] this IEnumerable<T> source, Func<T, ulong> selector)
{
return source.Select(selector).Sum();
}
[CheckParameters]
public static ulong? Sum<T>([NotNull] this IEnumerable<T> source, Func<T, ulong?> selector)
{
return source.Select(selector).Sum();
}
I used some custom PostSharp attributes here to do the parameter validation, but you can just as easily substitute them with if null then throw exception code blocks.
Using the dynamic type in .Net 4 you can make these extension methods even more useful by making them usable with other value types too.
Traditionally for extension methods like Sum, you’d have to provide an overload for each numeric value type (int, uint, long, etc.) because these numeric value types don’t have a common super type which defines the numeric operators +, -, /, *, etc.
Fortunately, you can now negate this compile time limitation by making it a runtime decision using the new dynamic capabilities:
public static T Sum<T>(this IEnumerable<T> source) where T : struct
{
return source.Aggregate(default(T), (current, number) => (dynamic) current + number);
}
public static T? Sum<T>(this IEnumerable<T?> source) where T : struct
{
return source.Where(nullable => nullable.HasValue)
.Aggregate(
default(T),
(current, nullable) => (dynamic) current + nullable.GetValueOrDefault());
}
public static V Sum<T, V>(this IEnumerable<T> source, Func<T, V> selector) where V : struct
{
return source.Select(selector).Sum();
}
public static V? Sum<T, V>(this IEnumerable<T> source, Func<T, V?> selector) where V : struct
{
return source.Select(selector).Sum();
}
The obvious fallacy with this approach is that you can now pass custom structures with no defined + operator into these extension methods and no compile errors will be thrown, but a RuntimeBinderException will be thrown by the DLR at runtime with a message like this:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Operator ‘+’ cannot be applied to operands of type ‘xxx’ and ‘xxx’
Since migrating to Windows Server 2008 Datacenter for our Amazon EC2 instances I have noticed on many occasions that when a new instance is starting up RAC agent will cause the CPU to spike up to 100% for a good half an hour, at times the CPU spike never comes down and effectively renders the instance unusable..
After some digging around, I found this article which tells you how to disable the RAC agent:
http://dotnetwizard.net/tutorials/stop-racagent-from-hogging-your-pc-resources/
In case the link stops working in the future, here’s the 4 steps you need to do:
1. go to Control Panel –> Administrative Tools –> Computer Management
2. navigate to System Tools –> Task Scheduler –> Task Scheduler Library –> Microsoft –> Windows –> RAC
3. right click RAC, select View –> Show Hidden Tasks
4. right click on the displayed task, and select Disable