Thursday, November 11, 2010

Confused the compiler/runtime or what?

This was an innocent enough of a typo but it had me questioning whether the framework's string.Split() method was working with the remove empty entries option.

Line in question:
var parameterPairs = parameterValue.Split(new char['&'], StringSplitOptions.RemoveEmptyEntries).ToList();

The parameterValue being parsed was "&Token=8765"
I expected to get a result back of "Token=8765", but instead got back a value of "&Token=8765".

I was thinking was there a problem with RemoveEmptyEntries when the separator was the first character? Was there a problem with '&' as a separator? Both checked out. Then I noticed the typo. It should have been:

var parameterPairs = parameterValue.Split(new char[] {'&'}, StringSplitOptions.RemoveEmptyEntries).ToList();

And presto, the test passed. But that got me wondering, what was char['&'] resolving to? Why did the compiler allow it to compile, and why did string.Split() seem to merely ignore it at runtime?

I put in a precursor condition:
var test = new char['&'];

along with a breakpoint.

Curious...

1 comment:

  1. Mystery solved. The statement "new char['&']" would create an array of 38 empty chars. (Thanks Lance) The reason for the confusing debugger behaviour was that I hadn't noticed that it was running in Release mode. (I had previously been making updates in Configuration Manager.) Since the "test" variable was not actually used anywhere, it was optimized out of the build.

    ReplyDelete