13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Extension method syntax259extension method—just add the this keyword. List<strong>in</strong>g 10.3 shows the same class as <strong>in</strong>list<strong>in</strong>g 10.1, but this time with both methods as extension methods.List<strong>in</strong>g 10.3The StreamUtil class aga<strong>in</strong>, but this time with extension methodspublic static class StreamUtil{const <strong>in</strong>t BufferSize = 8192;}public static void CopyTo(this Stream <strong>in</strong>put,Stream output){byte[] buffer = new byte[BufferSize];<strong>in</strong>t read;while ((read = <strong>in</strong>put.Read(buffer, 0, buffer.Length)) > 0){output.Write(buffer, 0, read);}}public static byte[] ReadFully(this Stream <strong>in</strong>put){us<strong>in</strong>g (MemoryStream tempStream = new MemoryStream()){CopyTo(<strong>in</strong>put, tempStream);return tempStream.ToArray();}}Yes, the only big change <strong>in</strong> list<strong>in</strong>g 10.3 is the addition of the two modifiers, as shown <strong>in</strong>bold. I’ve also changed the name of the method from Copy to CopyTo. As we’ll see <strong>in</strong> am<strong>in</strong>ute, that will allow call<strong>in</strong>g code to read more naturally, although it does lookslightly strange <strong>in</strong> the ReadFully method at the moment.Now, it’s not much use hav<strong>in</strong>g extension methods if we can’t use them…10.2.2 Call<strong>in</strong>g extension methodsI’ve mentioned it <strong>in</strong> pass<strong>in</strong>g, but we haven’t yet seen what an extension method actuallydoes. Simply put, it pretends to be an <strong>in</strong>stance method of another type—the typeof the first parameter of the method.The transformation of our example code that uses StreamUtil is as simple as thetransformation of the utility class itself. This time, <strong>in</strong>stead of add<strong>in</strong>g someth<strong>in</strong>g <strong>in</strong>we’ll take it away. List<strong>in</strong>g 10.4 is a repeat performance of list<strong>in</strong>g 10.2, but us<strong>in</strong>g the“new” syntax to call CopyTo. I say “new,” but it’s really not new at all—it’s the same syntaxwe’ve always used for call<strong>in</strong>g <strong>in</strong>stance methods.List<strong>in</strong>g 10.4Copy<strong>in</strong>g a stream us<strong>in</strong>g an extension methodWebRequest request = WebRequest.Create("http://mann<strong>in</strong>g.com");us<strong>in</strong>g (WebResponse response = request.GetResponse())us<strong>in</strong>g (Stream responseStream = response.GetResponseStream())Licensed to Rhona Hadida

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!