How do I check if an object contains a byte array? - c#

I'm having an issue with the following code.
byte[] array = data as byte[]; // compile error - unable to use built-in conversion
if (array != null) { ...
I only want to assign the data to array variable if the data is actually a byte array.

How about this:
byte[] array = new byte[arrayLength];
if (array is byte[])
{
// Your code
}

Try
if(data.GetType().Name == "Byte[]")
{
// assign to array
}

As soon as I asked this I realised that the type of data was not object.
Making it of type object (its coming in via a type converter in Silverlight) and it worked.

Related

c# error - Can not convert Array to byte array

I am trying cast a Json data to byte array and then save it in SQL image field, code is below
public string Post([FromBody] dynamic data)
{
foreach (var item in data)
{
imgPhoto1 = (byte[])item["Photo1"];
}
}
But getting error Can not convert Array to byte array
byte[] imgPhoto1 = (byte[])item["Photo1"];
Values in field item["Photo1"] is look like below
[255,216,255,224]
any help will be appreciated
If your parameter data is JToken, then you need convert it to desired type.
Try to use:
var obj = item["Photo1"].ToObject<byte[]>();
And will be better explicit declare your parameter data as JToken.

Why is "System.Byte[]" coming when "byte[]" is entered?

I'm a beginner to programming and use C# to learn programming. When I enter this code
byte[] bytes={1,2,3};
Console.WriteLine(bytes);
the output isSystem.Byte[].
Why is that? How can I fix it?
foreach (byte b in bytes)
{
Console.WriteLine(b);
}
iteration - the repetition of a process or utterance.
As per the removed comment on your post, you need to iterate over each byte to get the value. As it is, you're simply printing out the type when you try and print an array and not it's elements.
byte[] bytes = { 1, 2, 3 };
foreach(byte b in bytes)
{
Console.Write(b);
}
I think that #Aquaballin beat me to the punch; we even use a similar method of iterating! :D
The console is writing out the string value of the byte array, which is "System.Byte[]".
You need to print out each item in the Byte array individually, which is most simply done like this:
foreach(Byte item in bytes)
{
Console.WriteLine(item));
}
Console.WriteLine generally expects a string. If the value or object passed in as parameter is of a different time it will convert the value or object internally to a string by calling its .ToString() method. The .ToString method of any array type will only return the type name, not its content. You presumably want to print out the content of the array. #Aquaballin's answer is almost what you tried to accomplish, except for the superfluous line breaks. I'll also add some commas as delimiters.
foreach (byte b in bytes)
{
Console.Write(b);
}
Console.WriteLine();
Console.WriteLine(obj) implicitly calls the ToString method on the passed parameter. In the case of a System.Byte[] (aka: byte[]) type, the ToString method is implemented ultimately by the System.Object base class. The code for that method (via ILSpy) is:
public virtual string ToString()
{
return GetType().ToString();
}
This reads the type information and calls ToString on the type object itself, which simply returns the name of the type.
As others have answered, in order to get a listing of the items within the array, you need to invoke an enumerator of some sort. There are many different ways in C#, the best option depends on your end goal.
you miss iteration
for (int i = 0; i < bytes.Length; i++)
{
Console.WriteLine(bytes[i]);
}

MSIL store a value of structure to return

I am using RemotingLite library (see at github) and have an issue with Proxy class factory.
In few words the issue is when generating code for return an ValueType objects like user defined structures.
Here a part of original code:
...
mIL.Emit(OpCodes.Ldloc, resultLB.LocalIndex); //load the result array
mIL.Emit(OpCodes.Ldc_I4, 0); //load the index of the return value. Alway 0
mIL.Emit(OpCodes.Ldelem_Ref); //load the value in the index of the array
if (returnType.IsValueType)
{
mIL.Emit(OpCodes.Unbox, returnType); //unbox it
mIL.Emit(ldindOpCodeTypeMap[returnType]);
}
else
mIL.Emit(OpCodes.Castclass, returnType);
}
mIL.Emit(OpCodes.Ret);
ldindOpCodeTypeMap is a dictionary with opcodes like OpCodes.Ldind_U2 etc. So it works only for standard MSIL types like Int16, Int32 etc. But what I need to do if I need to push to stack then return a custom ValueType value (for example - Guid - size is 16 bytes)?
For example:
...
mIL.Emit(OpCodes.Unbox, returnType); //unbox it
OpCode opcode;
if (ldindOpCodeTypeMap.TryGetValue(returnType, out opcode))
{
mIL.Emit(ldindOpCodeTypeMap[returnType]);
}
else
{
// here I getting the size of custom type
var size = System.Runtime.InteropServices.Marshal.SizeOf(returnType);
// what next?
}
...
Here I have get a size of custom ValueType value. So how Load a value of custom ValueType onto the evaluation stack indirectly like Ldind_x opcodes do that?
Thanks!
Ldobj will do what you want. But you could also replace the entire conditional with Unbox_Any: it will do everything you need for a value type or a reference type.
The full replacement for your posted code would be:
...
mIL.Emit(OpCodes.Ldloc, resultLB.LocalIndex); //load the result array
mIL.Emit(OpCodes.Ldc_I4, 0); //load the index of the return value. Alway 0
mIL.Emit(OpCodes.Ldelem_Ref); //load the value in the index of the array
mIL.Emit(OpCodes.Unbox_Any, returnType);
mIL.Emit(OpCodes.Ret);

C# - Convert Object to Array to get Data by Index

I have a webservice that returns me an object with data
object data = _wsUsuario.CarregarDadosUsuario(_view.Usuario);
This object, called data, returns me the following:
[0] 84
[1] Marcelo Camargo
[2] myemail#myprovider.com
[3] 2
If I try to do
MessageBox.Show(data[0]);
Then the compiler says me:
Cannot apply indexing to an expression of type 'object'. I searched and wonder if there is a way to convert this object of strings and integers to an array. Can you give me a hand?
Assuming the data is an array of strings, then you would need to cast it accordingly:
object[] oData = (data as object[]) ?? new object[0];
This will TRY to cast to object[] but if it isn't castable, it will return null and the null coalescing operator ?? will return an empty object array instead.
An object doesn't have an indexer. An array does.
I think you downcasted the functions return type from a specific strong type object(some kind of array) into a basic 'object'.
What should happen:
// res should be an array
CarregarDadosUsuarioReturnType res = _wsUsuario.CarregarDadosUsuario(_view.Usuario);
MessageBox.Show(res[0]);
If, for any reason this service implicitly recieves an object simply cast this into:
object data = _wsUsuario.CarregarDadosUsuario(_view.Usuario);
var arr = data as ArrType[]; // where ArrType = the array type.
MessageBox.Show(arr[0]);

How to convert a JavaScript array of doubles to a .NET array of doubles?

What is the best way to convert a JavaScript array of doubles
return [2.145, 1.111, 7.893];
into a .NET array of doubles, when the Javascript array is returned from a webbrowser controls document object
object o = Document.InvokeScript("getMapPanelRegion");
without using strings and parsing?
The object returned is of type __ComObject as it is an array being returned. The array will be a fixed size as I am using this to return three values back to the calling code. My current solution is to return a | deliminated string of the three value, I then split and parse the string to get my three doubles. If possible I would like to not have to use the string manipulation as this feels like a hack.
From MSDN (HtmlDocument.InvokeScript Method):
The underlying type of the object returned by InvokeScript will vary. If the called Active Scripting function returns scalar data, such as a string or an integer, it will be returned as a string ...
It seems that integers will be returned as string, you could asume that the same applies to doubles.
EDIT:
I forgot that you were talking about an array. Anyhow, MSDN continues:
... If it returns a script-based object, such as an object created using JScript or VBScript's new operator, it will be of type Object ...
So it seems that you will get an object instead, but that doesn't help the fact that you will have to convert it inside your C# code.
EDIT 2:
As for the conversion of the actual ComObject. After reading this which is about Excel, but it still returns a ComObject, it seems that your current aproach with the string seems like the simpler one. Sometimes a hack is the best solution :D
This "problem" amounts to transforming VARIANT into an C# array. For this probably the easiest way is to use reflection. Here is how:
private static IEnumerable<object> SafeArrayToEnmrble (object comObject)
{
Type comObjectType = comObject.GetType();
// spot here what is the type required
if (comObjectType != typeof(object[,]))
// return empty array, throw exception or whatever is your fancy
return new object[0];
int count = (int)comObjectType.InvokeMember("Length", BindingFlags.GetProperty, null, comObject, null);
var result = new List<object>(count);
var indexArgs = new object[2];
for (int i = 1; i <= count; i++)
{
indexArgs[0] = i;
indexArgs[1] = 1;
object valueAtIndex = comObjectType.InvokeMember("GetValue", BindingFlags.InvokeMethod, null, comObject, indexArgs);
result.Add(valueAtIndex);
}
return result;
}

Categories

Resources