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]);
}
Related
I have a List that I'm adding 3 bytes to one of which is the length of a string that I'm dynamically passing to my method. How can I determine the length of that string and convert the int into a value that would be accepted in my list.add() method.
Code below:
string myString = "This is a sample string...I need its length";
int theLength = myString.Length;
List<byte> lb = new List<byte>();
lb.Add(0x81);
lb.Add(theLength); // this doesn't work
lb.Add(0x04);
TIA
Try this:
lb.AddRange(BitConverter.GetBytes(theLength))
Of course, you may decide you only need the least significant bit, in which case you could do a simple cast, or index into the result of GetBytes(), which will be 4 bytes long in this case.
More on BitConverter:
http://msdn.microsoft.com/en-us/library/system.bitconverter.getbytes.aspx
Provided the string's length is within the byte range:
lb.Add((byte)theLength);
You have to cast your length into a byte:
lb.Add((byte)theLength);
But as you might guess, your length won't always fit into a single byte. Be more specific about what you expect to do with your list of bytes, we might could provide a better answer (such as using BinaryReader/BinaryWriter instead of a list of bytes).
I've been investigating the out keyword in C# after reading the section about it in C# in Depth. I cannot seem to find an example that shows why the keyword is required over just assigning the value of a return statement. For example:
public void Function1(int input, out int output)
{
output = input * 5;
}
public int Function2(int input)
{
return input * 5;
}
...
int i;
int j;
Function1(5, out i);
j = Function2(5);
Both i and j now have the same value. Is it just the convenience of being able to initialize without the = sign or is there some other value derived that I'm not seeing? I've seen some similar answers mentioning that it shifts responsibility for initialization to the callee here. But all that extra instead of just assigning a return value and not having a void method signature?
Usually out is used for a method that returns something else, but you still need to get a different value from the method.
A good example is Int32.TryParse(input, out myVar) it will return true if it was successful and false otherwise. You can get the converted int via the out parameter.
int myOutVar;
if (Int32.TryParse("2", out myOutVar))
{
//do something with the int
}else{
//Parsing failed, show a message
}
The out / ref keywords in C# should only be used when you need to return multiple values. Even then you should first consider using a container type (such as Tuple) to return multiple values before you revert to out / ref. Whenever you're returning a single value it should just be returned.
A lot of times, using out can help by giving you a slight performance gain.
Consider the TryGetValue method on IDictionary (say myDictionary is an IDictionary<string, string>) Rather than doing this:
string value = String.Empty;
if (myDictionary.ContainsKey("foo"))
{
value = myDictionary["foo"];
}
Both ContainsKey and the indexer need to look up the key in the dictionary, but you can avoid this double-lookup on the positive case by going:
string value;
if (!myDictionary.TryGetValue("foo", out value))
{
value = String.Empty;
}
IMO, that's a decent reason for using out parameters.
Unfortunately we cannot do something like below in C#:
a,b = func(x,y,z);
something that we do in Python or other languages. out kind of overcomes that.
F# has overcome this with tuples I believe.
PS: Returning multiple values from a function might not be good always. Tiny types are good most of the times - http://www.martinfowler.com/bliki/DataClump.html
For example, Int32.TryParse returns boolean if it parsed correctly and with the out parameter changes the value. If the parsed value is 0 and it returns true it means the value you sent to parse was 0. If it returns false then the parser failed.
Some of it is for clarity. Take the TryParse() methods, like
Int32.TryParse("3", out myInt);
This returns a bool that indicates whether the string was able to be parsed into an int.
If you just had
Int32.TryParse("3", myInt);
What happens when that's called? Is myInt assigned? Does TryParse return an int?
It's not readily apparent. But if I have an out parameter, then I know that the value is getting assigned, and that the return is something else.
Basically you do something like (my database read)
if (ReadSingle<UserRecord>(cmd, out user))
Cache.Insert(cacheId, user, null,
DateTime.MaxValue, TimeSpan.FromMinutes(3));
Or else you do something like:
user = ReadSingle<UserRecord>(cmd);
if(null != user)
// Cache.Insert ...
It simplifies the code a little to use a boolean result (that a record was read from the database) and get the actual record into the variable via the out keyword.
I'm trying to figure out what I'm doing wrong here, but I can't seem to. I have this method that takes in a string and reverses it. However, when I print out the reversed string from the caller method, I just get "System.Char []" instead of the actual reversed string.
static string reverseString(string toReverse)
{
char[] reversedString = toReverse.ToCharArray();
Array.Reverse(reversedString);
return reversedString.ToString();
}
Calling ToString on a T array in .NET will always return "T[]". You want to use this instead: new string(reversedString).
By calling ToString you just get the default implementation that every class inherits from object. .NET can't provide a special implementation just for an array of char; the override would have to apply to all types of array.
Instead, you can pass the array to String's constructor, return new String(reversedString).
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;
}
I'm using a third party library. One of the methods requires passing an array via ref that will be populated with some info. Here's the definition for the method:
int GetPositionList(ref Array arrayPos)
How do I construct arrayPos so that this method will work? In the library's not so complete documentation it defines the method as such:
long GetPositionList(structSTIPosUpdate() arrayPos)
I've tried this but of course I'm getting errors:
System.Array position_list = new System.Array();
sti_position.GetPositionList(ref position_list);
Any ideas?
This is the Sterling Trader Pro ActiveX API, right? Did you create an Interop dll using tlbimp.exe? The GetPositionList API expects an array which will hold structs of type structSTIPositionUpdate. Normally an out modifier is used if the callee initializes the passed-in data, and ref if the data is to be initialized. According to the meaning of the API the modifier should be out, so that this should work:
structSTIPositionUpdate [] entries = new structSTIPositionUpdate[0]; // or null
num_entries_returned = GetPositionList(ref entries);
Alternatively, try creating an array of these structs which is big enough to hold the expected number of entries, then pass it to the function:
structSTIPositionUpdate [] entries = new structSTIPositionUpdate[100]; // say
num_entries_returned = GetPositionList(entries);
Update: If you are getting type mismatches with System.Array, try
System.Array entries = Array.CreateInstance(typeOf(structSTIPositionUpdate), N);
where N is the number of elements in the array.
To create an instance of an Array you can use the CreateInstance method:
Array a = Array.CreateInstance(typeof(Int32), 10);
GetPositionList(ref a);
The type, dimension and size of the array is something the library author should document. The GetPositionList may be badly designed and simply create a new Array for you essentially meaning that the library author should have used out instead of ref. In that case you can use a null array:
Array a = null;
GetPositionList(ref a);
You can use Array.CreateInstance
This may help you:
http://msdn.microsoft.com/en-us/library/szasx730%28VS.80%29.aspx
...although I don't understand why an object needs to have the "ref" keyword. Objects are passed by reference, so this should work anyway, without making use of the ref keyword. For arrays like int[] or string I understand this...
This works:
Array position_list = new int[]{1, 3, 5, 5,6};
sti_position.GetPositionList(ref position_list);
I also using Sterling Trader API. I use this code:
private structSTIPositionUpdate[] PositionList {
get {
Array arrayPos = null;
_position.GetPositionList(ref arrayPos);
return (structSTIPositionUpdate[]) arrayPos;
}
}