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#?
Related
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
I just got thrown into a C# project for solidWorks that I'm not too comfortable with. I need to convert this out System.Array to a string[]. Then that string is called and converted from out System.Array to out EdmLib.EdmBatchError2[].
TLDR: out System.Array' to a string[].
Code:
private void GetSerialNumberGenerators()
{
IEdmSerNoGen7 utility = this.m_vault.CreateUtility(EdmUtility.EdmUtil_SerNoGen) as IEdmSerNoGen7;
Array ppoRetNames = Array.CreateInstance(typeof(string[]), 0);
utility.GetSerialNumberNames(out ppoRetNames);
this.comboBoxSerialNumber.DataSource = (object) ppoRetNames;
}
Severity Code Description Project File Line Suppression State
Error CS1503 Argument 1: cannot convert from 'out System.Array' to 'out string[]'
It's simple as
string[] ppoRetNames;
GetSerialNumberNames(out ppoRetNames);
This is the way to declare a string[]. Don't initialize it yourself because GetSerialNumberNames will do it (out-parameter). No need to use Array.CreateInstance.
Apart from that you are creating a jagged array because you pass typeof(string[]) not typeof(string). You need a one dimensional array so this would be correct:
Array someArray = Array.CreateInstance(typeof(string), 0);
string[] ppoRetNames = (string[])someArray; // so a cast is what was missing
GetSerialNumberNames returns System.Array of type EdmBatchError2, which is a structure of 4 ints, so I don't know how that would cast to a string[] in a usable sense. Here is what I do:
utility.GetSerialNumberNames(out Array ppoRetNames);
foreach(EdmBatchError2 batchError in ppoRetNames) {
// construct error message with below variables for each error
//batchError.mlFileID;
//batchError.mlFolderID;
//batchError.mlVariableID;
//batchError.mlErrorCode;
}
I have the following simplified function:
private IEnumerable<byte> Encode(IEnumerable<byte> Input)
{
computation();
return result;
}
The Buffer:
byte[] BufferHex = {0x00};
IEnumerable<byte> result1;
richtext.AppendText(Encoding.UTF8.GetString(result1));
The error is at the last line saying: Conversion IEnumerable to byte[] not possible.
I have tried several things but still no success. Any help will be appreciated.
As it says it is expecting a byte[] as parameter, so you need to convert your IEnumerable<byte> to a byte[], you can do this using ToArray extension method:
richtext.AppendText(Encoding.UTF8.GetString(result1.ToArray()));
Encoding.UTF8.GetString() expects a parameter of type byte[], not IEnumerable<byte>. So simply change that line to
richtext.AppendText(Encoding.UTF8.GetString(result1.ToArray()));
ToArray() is a LINQ extension that converts an IEnumerable<T> into a T[].
I don't know if this will be suitable for your case, but you can use Convert.ToBase64String(byte[] bytes) and don't forget to call ToArray(), on your enumerable
I am porting managed C++ code to C#. I am trying to convert a piece of code where the function parameter is a byte array but then within the function body, it is typecasted to a structure pointer and used throughout the function.
How do you typecast a native data type to a structure in c# without having to use unsafe/pointers?
Code:
public byte[] Mail( byte[] mailbox, byte[] sst )
{
pin_ptr<unsigned char> header = &mailbox[0];
PCMP_MAIL_HEADER pHeader = (PCMP_MAIL_HEADER)mailbox;
int BodySize = (int) pHeader.MailLength;
...
}
PCMP_MAIL_HEADER is the user defined strucutre. I need to typecast mailbox to that structure.
How can i convert this VBNet code into C#? (ByteToImage is a User Defined Function use to convert Byte Array into Bitmap.
Dim Bytes() As Byte = CType(SQLreader("ImageList"), Byte())
picStudent.Image = jwImage.ByteToImage(Bytes)
I tried
byte[] Bytes = Convert.ToByte(SQLreader("ImageList")); // Error Here
picStudent.Image = jwImage.ByteToImage(Bytes);
but it generates an error saying: Cannot implicitly convert type 'byte' to 'byte[]'
What i am doing is basically converting an Image from database to byte array and displaying it on the picturebox.
byte[] Bytes = (byte[]) SQLreader("ImageList");
picStudent.Image = jwImage.ByteToImage(Bytes);
Try this
byte[] Bytes = (byte[])SQLreader("ImageList");
Hope this helps
The problem is you have an array of bytes (byte[] in C# and Byte() in VB.Net) but the Convert.ToByte call just returns a simple byte. To make this work you need to cast the return of SQLreader to byte[].
There is no perfect analogous construct for CType in C# but a simple cast here should do the trick
byte[] Bytes = (byte[])SQLreader("ImageList");
CType is the equivalent of a type cast, not an actual conversion.Besides, Convert.ToByte tries to convert its input to a single byte, not an array. The equivalent code is
byte[] bytes=(byte[])SQLreader("ImageList");