Friday 29 July 2011

The perils of 'ref' parameters

Arrghh! ref parameters! Don't you just love them? At least C# requires that you place the keyword ref in the calling code as well as the receiving code but even so ...

I had a nice one today. A swap object was passed as a ref parameter into a function which then called Clone_API. Now, under normal circumstances this works fine but this was a new swap and the code had been set by our code to zero. The Clone_API call did not, however, recognise the zero code and replaced it with the sicovam of the original instrument from which our working swap was cloned. Arrrghhh! Luckily our code fell over when it tried to save the instrument!

Lesson? Don't use ref parameters if at all possible and certainly not when it would be so easy to return the cloned object from the function and then explicitly reassign it in the calling code.

Thursday 28 July 2011

Beware the yield'd iterator

In C# there are two types of iterator (as far as I know). One is an iterator into a container which is created by something akin to List<T>.GetEnumerator(). The other is the yield'd iterator and this is created by a function which yield returns each element in the sequence.

The issue is that the former can be reset but the latter cannot. Therefore, if you are using the latter you need to be very sure that it is only used the once. If a second loop through the sequence will be required then store the iterator in a list comme ca


List<T> l = new List<T>(myIterator);


and then use l instead.