Why does XmlTextReader fail on calling an unsupported Stream.Length?

I have an XmlTextReader, and I pass it in a System.Net.ConnectStream. If I enter the debugger, I can see that ConnectStream does not support the Length property and this throws a NotSupportedException.

Now, I subclass Stream and pass in an instance of my class. My class also throws NotSupportedException on the get() accessor of Length, but this time all my unit tests fail with a NotSupportedException.

The XmlTextReader documentation does not say it requires a Stream supporting Length, and it clearly can use one that doesn't - what is going on?

(This is .NET 3.5 Client)

Jon Skeet
people
quotationmark

If a Stream returns true from CanSeek, it assumed that Length, SetLength, Position and Seek are all supported. Some code may test CanSeek and use the result to optimize its behaviour - as seems to be the case here. When you return true from CanSeek but then throw an exception in Length, that's breaking the not-terribly-well-documented contract of Stream.

If you can't support the Length property, it's best to return false from CanSeek.

people

See more on this question at Stackoverflow