"Magic" null argument testing

Warning: here be dragons. I don’t think this is the right way to check for null arguments, but it was an intriguing idea. Today on Stack Overflow, I answered a question about checking null arguments. The questioner was already using an extension similar to my own one in MiscUtil, allowing code like this: public void DoSomething(string name) {     name.ThrowIfNull("name");     // Normal code here } That’s all very well, but it’s annoying to have to repeat the name part. Now in an ideal world, I’d say it would be nice to add an attribute to the parameter and have the … Continue reading "Magic" null argument testing

API design: choosing between non-ideal options

So, UnconstrainedMelody is coming on quite nicely. It now has quite a few useful options for flags enums, "normal enums" and delegates. However, there are two conflicting limitations which leave a couple of options. (Other related answers on Stack Overflow have suggested alternative approaches, basically.) Currently, most of the enums code is in two classes: Flags and Enums. Both are non-generic: the methods within them are generic methods, so they have type parameters (and constraints). The main benefit of this is that generic type inference only applies to generic methods, and I definitely want that for extension methods and anywhere … Continue reading API design: choosing between non-ideal options

Evil Code of the Day: variance and overloading

(Note that this kind of breakage was mentioned a long time ago in Eric Lippert’s blog, although not in this exact form.) Whenever a conversion becomes available where it wasn’t before, overload resolution can change its behaviour. From C# 1 to C# 2 this happened due to delegate variance with method group conversions – now the same thing is true for generic variance for interfaces. What does the following code print? using System; using System.Collections.Generic; class Base {     public void Foo(IEnumerable<string> strings)     {         Console.WriteLine(“Strings”);     } } class Derived : Base {     public void Foo(IEnumerable<object> objects)     {         Console.WriteLine(“Objects”);     } } class Test {     static void Main()     {         List<string> strings = new List<string>();         new Derived().Foo(strings);     } } The correct answer is “it … Continue reading Evil Code of the Day: variance and overloading