0

I have this function in c#:

public string CommitDocument(string extension, byte[] fileBytes)
{
   // some code here
}

I'm trying to call this function like this:

  CommitDocument("document.docx", byte [1493]);

I'm getting an error: "Invalid expression term 'byte'". How can I pass a value to the parameter of type byte?

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
IT Developer
  • 23
  • 2
  • 10

2 Answers2

4

The byte[] is an array of bytes and you need to allocate the array first with 'new'.

byte[] myArray = new byte[1493];
CommitDocument("document.docx", myArray);
Andrew B
  • 61
  • 6
-1

You defined CommitDocument as taking a byte array. A single byte is not convertible into a byte array. Or at least the Compiler is not doing that implicitly. There are a few ways around that limitation:

Provide a overload that takes a byte and makes it into a one element array:

public string CommitDocument(string extension, byte fileByte)
{
   //Make a one element arry from the byte
   var temp = new byte[1];
   temp[0] = fileByte;

   //Hand if of to the existing code.
   CommitDocument(extension, temp);
}

Otherwise turn fileBytes in a Params Parameter. You can provide any amount of comma seperated bytes to a Params, and the compiler will automagically turn them into an array. See Params Documentation for details and limits: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params

Marco
  • 2,007
  • 17
  • 28
Christopher
  • 9,634
  • 2
  • 17
  • 31
  • Nevermind this. Andrew B found the real issue. – Christopher Feb 09 '18 at 16:38
  • @StephenKennedy: I know. I just can not exclude that there is some mistake in the question, wich could make my answer right again :) So I upvoted the one for Andrew and leave it around for some time. – Christopher Feb 09 '18 at 16:44
  • @StephenKennedy: As this is to make a code example, I opted for the simpler code. Also I prefer to write like this. It gives me better lines at debugging. And the normal and JiT Compiler can still cut it out in release builds. – Christopher Feb 09 '18 at 16:58
  • Thank you @Christopher! I appreciate your help! – IT Developer Feb 09 '18 at 17:58