How can I pass a byte value in c# function [duplicate] - c#

This question already has answers here:
All possible array initialization syntaxes
(19 answers)
Closed 5 years ago.
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?

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);

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

Related

How to change an array in a function without changing the original array? [duplicate]

This question already has answers here:
Copy Arrays to Array
(7 answers)
Closed 1 year ago.
In C# and many other languages, if you pass an array to a function it passes the pointer/reference which means you can change the value of an array from inside a function.
From Microsoft:
Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.
I have a special case where I need to access and change an array's contents from a function but I do not want to change the original array. I thought this would be quite simple. I could set a new array equal to the old array and change the new array. This acts the same, however, because the new array is just a pointer to the old one.
static void AddToArray(string[] array) {
var newArray = array;
newArray[2] = "y";
}
static void Main(string[] args) {
string[] array = new string[5];
array[0] = "h";
array[1] = "e";
AddToArray(array);
}
If you print the contents of array at each step:
"he"
"hey" (inside function)
"hey" (after function call)
I've done a lot of research online but somehow haven't found many other people who needed help with this. Advice is greatly appreciated!
You are not creating your array using "new" Keyword inside function. Change below line -
var newArray = array;
To
var newArray = new string[args.Length];
and after creating this as a new array, you can copy the values from args (passed) array

Need a function to reverse an array in C# [duplicate]

This question already has answers here:
Reverse elements in an array
(6 answers)
Closed 6 years ago.
I need to create a function that receives an array items and reverses the order of items in the array and returns it.
Basically if I have an array ['cat', 'dog', 'bird', 'worm'] the function should return an array of ['worm','bird','dog','cat'].
So far I get lost in the function language... I have this.
//Split a string into an array of substring
string avengersNames = "Thor;Iron Man;Spider-Man;Hulk;Hawk Eye";
//Creat an array to hold substring
string[] heroArray = avengersNames.Split(';');
foreach (string hero in heroArray)
{
Console.WriteLine(hero);
}
//Parameter is Array of items
//At a loss when trying to incorporate an array into this function.
public static string[] heroList = new string[5];
{
}
Array.Reverse(heroArray); // can do trick for you
Use Array.Reverse function
string[] heroArray = avengersNames.Split(';');
Array.Reverse(heroArray );

Problems with an overloaded function inside a Generic Function

I am writing a function to help serialize data to pass through a socket. I wanted to write a small function that would serialize one item.
private byte[] SerializeOne<T>(T data)
{
byte[] oneItem = new byte[Constants.ONE_ITEM_BUFFER];
oneItem = BitConverter.GetBytes(data);
if (BitConverter.IsLittleEndian)
oneItem.Reverse();
return oneItem; }
The problem is BitConverter alwaysassumes data is a type bool and throws this error: Argument 1 cannot convert from T to bool. Am I missing some syntax to force BitConverter to use the T type or is this not possible in C#?

C#: how to copy a large array of structs efficiently? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C#: Any faster way of copying arrays?
I have an array of structs like this:
struct S
{
public long A;
public long B;
}
...
S[] s1 = new S[1000000];
...
S[] = new S[s1.Length];
// Need to create a copy here.
I can use unsafe mode and copy the source array of structs to a byte array and then from byte array to destination array of structs. But that means I will have to allocate a huge intermediate byte array. Is there a way to avoid this? Is it possible to somehow represent a destination array as a byte array and copy directly there?
unsafe
{
int size = Marshal.SizeOf(s0[0]) * s0.Length;
byte[] tmp = new byte[size];
fixed (var tmpSrc = &s0[0])
{
IntPtr src = (IntPtr)tmpSrc;
Marchal.Copy(tmpSrc, 0, tmp, 0, size);
}
// The same way copy to destination s1 array...
}
In case of Buffer.BlockCopy, it copies bytes[] to byte[] and not logical elements in array.
But this is really dependent on case to case.
Please test your code with Array.Copy first and see.

What is a equivalent of Delphi FillChar in C#?

What is the C# equivalent of Delphi's FillChar?
I'm assuming you want to fill a byte array with zeros (as that's what FillChar is mostly used for in Delphi).
.NET is guaranteed to initialize all the values in a byte array to zero on creation, so generally FillChar in .NET isn't necessary.
So saying:
byte[] buffer = new byte[1024];
will create a buffer of 1024 zero bytes.
If you need to zero the bytes after the buffer has been used, you could consider just discarding your byte array and declaring a new one (that's if you don't mind having the GC work a bit harder cleaning up after you).
If I understand FillChar correctly, it sets all elements of an array to the same value, yes?
In which case, unless the value is 0, you probably have to loop:
for(int i = 0 ; i < arr.Length ; i++) {
arr[i] = value;
}
For setting the values to the type's 0, there is Array.Clear
Obviously, with the loop answer you can stick this code in a utility method if you need... for example, as an extension method:
public static void FillChar<T>(this T[] arr, T value) {...}
Then you can use:
int[] data = {1,2,3,4,5};
//...
data.FillChar(7);
If you absolutely must have block operations, then Buffer.BlockCopy can be used to blit data between array locatiosn - for example, you could write the first chunk, then blit it a few times to fill the bulk of the array.
Try this in C#:
String text = "hello";
text.PadRight(10, 'h').ToCharArray();

Categories