views:

294

answers:

1

I was just going to use the FileUpload.FileBytes property but looking into the respective example in the MSDN library I'm confused about this part:

int fileLen;

// Get the length of the file.
fileLen = FileUpload1.PostedFile.ContentLength;

// Create a byte array to hold the contents of the file.
byte[] input = new byte[fileLen - 1];
input = FileUpload1.FileBytes;

(from here, I've omitted a few unimportant lines)

The new in this code looks for me like food for the garbage collector with no use. (Possibly big food if the file is large.) Why don't they simply write:

byte[] input = FileUpload1.FileBytes;

I am too new to .NET and C# to be brave enough to declare this simply as superfluous or a bad written example. Does it have any purpose (perhaps a performance benefit or so)? (Also I don't understand why they subtract 1 from fileLen.)

+2  A: 

The code samples from MSDN do vary in quality, and this is a good example of a bad coding sample.

As you say, it is easier to simply write:

byte[] input = FileUpload1.FileBytes;

And there is an error with the length of the byte array - no reason to subtract 1 from the posted length.

Oded
+1. Better answer than mine.
David Stratton
The linked example was from .NET 3.5. I just saw that in .NET 2.0 documentation is the same example but without the -1 error. Weird...Anyway: Thanks! I'm happy that I wasn't wrong with my understanding. (As mainly being a C++ programmer I still can't stay relaxed when I see the `new` keyword.)
Slauma