TheChaseMan's Frenetic SoapBox

Always looking for better ways to do things...

Bloated Example Code, Abstract Classes, and Strings Into MemoryStreams

Yesterday I was helping a friend of mine figure out what value to pass in to a function where the argument was of type Stream. System.IO is not a very intuitive namespace to begin with. Also, it's not readily apparent what to do in this case if you aren't familiar with inheritance (he's one of those VB guys). Specifically the concept that if you have a class C which derives from B which derives from A, if the argument type requirement is B then you can only pass in a B or a C. Not to mention that in this case it was more like an abstract class B required where you had to pass in an instance of C because C is a B and you can't instantiate B. Got it?  :-)

Anyway, I told him to look into passing a MemoryStream to the function. He then asked how to get a String into a MemoryStream, and since we were talking over IM, I promptly ran a Google search for "string into memorystream". The result in the list was the MSDN documentation for a MemoryStream class. He then replied, "well, gee...that's intuitive." Sensing the sarcasm, I decided to look at the example code and it was a lot more bloated (about 25 lines of sample code) than he was looking for. Fortunately, I can speak VB when I absolutely have to...

Dim memStream As New System.IO.MemoryStream(XMLMsg.Length)
memStream.Write(System.Text.UTF8Encoding.UTF8.GetBytes(XMLMsg), 0, XMLMsg.Length)

Just thought I'd share in case my blog ends up being indexed by Google and another poor SOB goes looking.  Then again, if you're a VB guy, why write it in 2 lines of code when you can write it in 25. Just kidding. :-)


Digg!

posted on Tuesday, October 18, 2005 9:46 PM

Feedback

# re: Bloated Example Code, Abstract Classes, and Strings Into MemoryStreams 10/19/2005 8:37 AM Stephen Toub

This might also be helpful:
http://msdn.microsoft.com/msdnmag/issues/05/07/NETMatters/

# re: Bloated Example Code, Abstract Classes, and Strings Into MemoryStreams 10/19/2005 8:57 AM Sean Chase

Excellent! Thanks for the link.