1, but this time with both methods as extension methods.
public static class StreamUtil
{
const int BufferSize = 8192;
public static void CopyTo(this Stream input,
Stream output)
{
byte[] buffer = new byte[BufferSize];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
}
public static byte[] ReadFully(this Stream input)
{
using (MemoryStream tempStream = new MemoryStream())
{
CopyTo(input, tempStream);
return tempStream.ToArray();
}
}
}
Yes, the only big change in listing 10.3 is the addition of the two modifiers, as shown in
bold. I??™ve also changed the name of the method from Copy to CopyTo. As we??™ll see in a
minute, that will allow calling code to read more naturally, although it does look
slightly strange in the ReadFully method at the moment.
Now, it??™s not much use having extension methods if we can??™t use them??¦
10.2.2 Calling extension methods
I??™ve mentioned it in passing, but we haven??™t yet seen what an extension method actually
does. Simply put, it pretends to be an instance method of another type??”the type
of the first parameter of the method.
The transformation of our example code that uses StreamUtil is as simple as the
transformation of the utility class itself. This time, instead of adding something in
we??™ll take it away. Listing 10.4 is a repeat performance of listing 10.
Pages:
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493