System.Int32[] displaying instead of Array elements [duplicate] - c#

This question already has answers here:
How can I print the contents of an array horizontally?
(12 answers)
How does the .ToString() method work?
(4 answers)
Closed 9 years ago.
I am trying to display array elements but always getting this output System.Int32[]
instead of integer elements.
using System.IO;
using System;
class Test
{
public static void Main()
{
int[] arr=new int [26];
for(int i = 0; i < 26; i++)
arr[i] = i;
Console.WriteLine("Array line : "+arr);
}
}

You could use string.Join
Console.WriteLine("Array line : "+ string.Join(",", arr));

You need to loop over the content and print them -
Console.WriteLine("Array line: ");
for(int i=0;i<26;i++)
{
arr[i]=i;
Console.WriteLine(" " + arr[i]);
}
Simply printing arr will call ToString() on array and print its type.

Printing an array will call the ToString() method of an array and it will print the name of the class which is a default behaviour. To overcome this issue we normally overrides ToString function of the class.
As per the discussion here we can not override Array.ToString() instead List can be helpful.
Simple and direct solutions have already been suggested but I would like to make your life even more easier by embedding the functionality in Extension Methods (framework 3.5 or above) :
public static class MyExtension
{
public static string ArrayToString(this Array arr)
{
List<object> lst = new List<object>();
object[] obj = new object[arr.Length];
Array.Copy(arr, obj, arr.Length);
lst.AddRange(obj);
return string.Join(",", lst.ToArray());
}
}
Add the above code in your namespace and use it like this: (sample code)
float[] arr = new float[26];
for (int i = 0; i < 26; i++)
arr[i] = Convert.ToSingle(i + 0.5);
string str = arr.ArrayToString();
Debug.Print(str); // See output window
Hope you will find it very helpful.
NOTE: It should work for all the data types because of type object. I have tested on few of them

You are facing this problem because your line
Console.WriteLine("Array line : "+arr);
is actually printing the type of arr. If you want to print element values you should use the index number to print the value like
Console.WriteLine("Array line : "+arr[0]);

Related

Reverse an Array order and print it C# [duplicate]

This question already has answers here:
How to reverse an array using the Reverse method. C# [closed]
(6 answers)
Closed 6 months ago.
using System;
using System.Linq;
namespace Array.ReversingArrayChar
{
class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
char[] symbol = input.Split(' ').Select(char.Parse).ToArray();
symbol.Reverse();
for (int a = 0; a <= symbol.Length - 1; a++)
{
Console.Write(symbol[a] + " ");
}
}
}
}
When I run the code I get the Array printed but not in reversed order even tho I used .Reverse(). It's probably a really simple mistake but it's too late at night for my brain to figure it out.
Enumerable.Reverse is a LINQ extension that returns the sequence reversed, so you have to assign it to a variable. But here you want to use Array.Reverse:
Array.Reverse(symbol);
Use Enumerable.Reverse if you don't want to modify the original collection and if you want to support any kind of sequence. Use List.Reverse or Array.Reverse if you want to support only these collections and you want to modify it directly. Of course this is more efficient since the method knows the size and you need less memory.
Oh Man..! you are almost there, your code is fine but you need to use the output of the .Reverse() method. since the method won't modify the actual collection, it will return the reversed array. you can try the following:
string input = "A S D R F V B G T";
char[] symbols = input.Split(' ').Select(char.Parse).ToArray();
foreach (var symbol in symbols.Reverse())
{
Console.Write(symbol + " ");
}
You will get the output as T G B V F R D S A

A two-dimensional ArrayList returns System.String[]

I have trouble with the value that arraylist returns.
I created a two-dimensional Arraylist that includes string arrays, when I try to get actual value of string arrays, I get System.String[] as output
instead of actual value of the arrays.
Why do I get System.String() as outuput?
Here is my code :
static void Main(string[] args)
{
string[] employee_1 = { "Employee1" };
string[] employee_2 = { "Employee2" };
ArrayList main_array = new ArrayList();
main_array.Add(employee_1);
main_array.Add(employee_2);
for (int i= 0; i < 2; i++)
{
Console.WriteLine(main_array[i]);
}
Console.ReadKey();
}
That is because when retrieving the items from an ArrayList what you are getting is a reference to an object instead of the actual type. Thus when printing it is calls the ToString of object (which prints the type's name) and not the string you want. In addition when printing a collection (like you are doing in your WriteLine command) you need to specify how to so do because it's default implementation is also as object's. You can use string.Join to print all items in the nested array.
To correct this first cast to string[] ( as string[]) and then print, or better still is to work with the list object instead: List<string[]>. To read more see:
ArrayList vs List<> in C#
What is the difference between an Array, ArrayList and a List?
So:
var mainCollection = new List<string[]> { new string[] { "Employee1" },
new string[] { "Employee2" }};
for (int i = 0; i < mainCollection.Count; i++)
{
Console.WriteLine(string.Join(", ", mainCollection[i]));
}
Console.ReadKey();
As a side note do not loop to 2 but instead by the number of items in the collection. See: What is a magic number, and why is it bad?
This is the default behaviour of ToString() function for an array.
To print the employees names, you need to iterate the array:
for (int i= 0; i < 2; i++)
{
foreach(string employee in main_array[i]) {
Console.WriteLine(employee);
}
}
The problem is here, ArrayList always take input as an object. So, when you add string array at an ArrayList, it take an object instead of string array.
So, you should convert this object to string array and print it.
like below:
for (int i = 0; i < 2; i++)
{
Console.WriteLine(string.Join(", ", main_array[i] as string[]));
}
or may use below(both are same):
for (int i = 0; i < 2; i++)
{
foreach (string employee in main_array[i] as string[])
{
Console.WriteLine(employee);
}
}
Because you have string[] type elements in outer ArrayList.
The best examples to enumerate are in answers above. If you realy need string content of string to be wtitten you should use
Console.WriteLine(((string[])main_array[i])[0]);
main_array is a two position ArrayList, each position contains a string[] this is, a string array.
If you use main_array[0], this is a reference to employee_1 which is a string array.
You should be able to reference the array strings by using main_array[0][0]
Try this:
foreach(var strArray in main_array)
{
// strArray is a string array
foreach(var stir in strArray)
{
// star is a string
Console.WriteLine(str);
}
}

c# custom serialization and deserialize simple class

i have this class
class MyClass{
int x;
byte[] arr;
}
I want to serialize it to text file but on custom way.
I want before I write the x value i want to write : the x value is: x.
and to do some manipulate on the arr (like +1 on every value) and move tab.
and then " the value again is" the value of X "have a nice day" with tab
how can i serialize like this to txt file,
and how can i deserialize from txt file like that to MyClass?
for example: x=4, arr={1,2,3}
the txt file will be
the value of X is: 4
arr is: 2,3,4
the value again is:5 have a nice day
how can i do this please?
i don't want to do special Get property for that var , because on my program i use this Get .
Serializing is different than what you are trying to do, but if you want special formatted output, some would do an override of the ToString() method, but you can just create another method something like...
public string textOutput()
{
var sb = new StringBuilder();
sb.AppendFormat("the value of X is: {0}\r\n arr is: ", x);
for (var i = 0; i < arr.Length; i++)
sb.AppendFormat("{0}{1}", i == 0 ? "" : ", ", arr[i]);
// don't know where your 5 value is coming from though... but place-holdered it
sb.AppendFormat("\r\n the value again is: {0} have a nice day", 5);
return sb.ToString();
}
and write your output as needed. Or you could create this as its own getter property and that too.

c# "method name expected" error when attempting to use a List<string> in a static void method [duplicate]

This question already has answers here:
Getting a list item by index
(6 answers)
Closed 5 years ago.
I'm trying to write a method that takes a List that contains two elements and checks that those elements are the same. I'm trying to set string variables equal to the indexed positions of the elements in the list and then use an if statement to determine if those elements are equal.
The problem I am having is that when attempting to call the list at all I get a "method name expected error".
Relevant code below:
static void CompareJson(List<string> jList)
{
string j = jList(0);
string k = jList(1);
if (j == k)
{
Console.WriteLine("");
}
else
{
Console.WriteLine("");
}
}
It's entirely possible that I'm going about this the wrong way, if so is there a better way to accomplish this?
As #Rufus points out, you need to use square brackets to access list elements by index, similar to accessing elements of an array:
static void CompareJson(List<string> jList)
{
string j = jList[0]; // jList member index 0
string k = jList[1]; // jList member index 1
if (j == k)
{
Console.WriteLine("");
}
else
{
Console.WriteLine("");
}
}

Is there any way to initialize several variables from one array? [duplicate]

This question already has answers here:
c# multi assignment
(7 answers)
Closed 8 years ago.
In some languages it is possible to initialize several variables at the same time from an array.
For example in PHP you can do something like this:
$array = array('a', 'b', 'c');
list($a, $b, $c) = $array;
Is it possible to do this in C# as well?
I want to apply this on a program where I read all lines from a file where I know every line is two words only (never more, never less).
I know I can create the function myself (and sending in variables by reference with outkeyword) but I would like to know if any built in functionality exists for it.
I would like to know this mostly for the reason that if it is possible the code might be more readable for other developers.
In C#,
string[] arr1 = new string[] { "one", "two", "three" };
string s1 = arr1[0];
string s2 = arr1[1];
string s3 = arr1[2];
If readability is the issue and if I understand you correctly - I don't know of an in-built way. But you can create a function for that.
void Doit(out string one, out string two, string[] input)
{
one = input[0];
two = input[1];
}
And use it thus:
string[] s = new string[] { "First", "Second" };
string a, b;
Doit(out a, out b, s);
I just realized that you don't need my answer. (I had initially understood "I know I can create the function myself..." differently.) Perhaps, though, it can help someone else.
char[] array = new char[] {'a','b','c'};
As far as I know there is no buit-in way to do that.
Maybe a good way to implement that functionality is by using extension methods in order to improve readability.
Simply write the needed code in a extension method that can be attached to the type you want to initialize like a list in your example above and take an array as input to that function:
public static class Extensions {
public static void initFromArray<T> (this List<T> list, T[] array) {
for (int i = 0; i < array.Length; i++) {
list[i] = array[i];
}
}
}
Then you can use this method for example like in the following:
int[] array = new int [] { 1, 4, 6, 2, 5 };
List<int> list = new List<int>();
for (int i = 0; i < 4; i++) list.Add(0);
list.initFromArray<T>(array);

Categories