blog: Operator overloading madness

Some madness concerning operator overloading in C# that I tripped over today: Let’s say we (tragically) have to work with XML stuff in a certain namespace. You define the namespace to use it later.

using System;
using System.IO;
using System.Xml.Linq;

namespace Madness {
	public class WTF {
		public static void Main(String[] args) {
			XNamespace foo = "foo";
			Console.WriteLine(foo + "bar");
		}
	}
}

You combine the namespace with some element name to arrive at your destination. The code sits for a while, later you decide to look at it again. You’re in a fit to throw out everything that is not needed, so you replace the concrete type XNamespace for implicit typing with var.

using System;
using System.IO;
using System.Xml.Linq;

namespace Madness {
	public class WTF {
		public static void Main(String[] args) {
			var foo = "foo";
			Console.WriteLine(foo + "bar");
		}
	}
}

After all, this should be the same, right? Wrong.

0 % ./madness
{foo}bar

0 % ./madness2
foobar

The reason: The first version implicitly converts a string to an XNamespace and uses the + operator provided by that class. In the second version, foo is of type string and the normal string concatenation is used. The combination of implicit conversion at assignment and overloaded ‘+’ operators really made this one hard to spot.

Posted in CSharp Programming
2017-03-24 22:24 UTC