Thursday, March 5, 2009

theothermike.printf("hello\n") && lessons(XmlSerializer)

This is my first article here, so I figure I'd do a little introduction first. I'm a professional software developer/geek, with expertise mainly in Perl and *nix environments. I've been toying around with Java and C# in the last couple of years, and more recently, I've started using C#/.NET at my day-job in a specific project.... which brings me to my first post.

While working on making a SOAP request and using the XML serialization facilities in .NET, I spent the better part of a day tracking down why all of a sudden my code had started throwing runtime exceptions when changing a class member from being an ArrayList to a generic List<SomeClass>

Thinking at first that the serialization services didn't actually work with generic collections, I had found several examples that proved otherwise..

Now keep in mind that I'm fairly new to Visual Studio (this project is in 2005), and IDEs in general as I had mainly been using Emacs in a terminal window before. So, when I was presented with the exception dialog, I was extremely annoyed at how many 'levels' I had to dig into the dialog to actually get to the exception information I needed. For some reason, it doesn't word wrap either, and even stretching the dialog across my 2 monitor setup doesn't reveal everything in the exception.

Almost ready to give up using generic collections, I started modifying the code to use ArrayList and arrays[], but cleaner than it had been before.

Now for some reason, the GUI was STILL throwing an exception... but at least it 'bubbled' up to a different exception dialog that would actually let me see the text of the entire exception*.

Way down in the stack, I saw the error message causing my problems wasn't related to the fact that I was using generic collections, but rather due to the fact that the class used in the generic collection (ie. SomeClass) didn't have a default constructor anymore since I had created another constructor to take parameters for convenience. This does make perfect sense after I realized my mistake, but it didn't even occur to me as I'm still fairly new to C# (I had assumed the default constructor would still be there even though I didn't define it)

Adding a default constructor of course took care of the problem, and I reverted back to using List instead of ArrayList.

Applying some tips from pjulien, I also made the class 'sealed' and exposed the List using IList instead ..... much nicer:)

... live and learn

* of course you can see the entire exception in the 'output' window of VS, but this I learned after the fact

No comments: