0

I'm having problems with arrays in C#

Inside my class when I type in

>>> public static void Main(string[] args) {
    Console.WriteLine (new string[] { "I", "Like", "π" });
}

The console says

System.String[]

Instead of the array I pass in.

What I'm trying to do is fit an array into a method like so:

>>> public static void Main(string[] args) {
    DoSomething ({ "I", "Like", "π" });
}

>>> public static int DoSomething(string[] array) {
    for (int i = 0; i > array.Length; i++) {
        Console.WriteLine (array [i]);
    }
}

I get an error saying

Unexpected symbol '{' on 'DoSomething ({ "I", "Like", "π" });'

How do I fix these errors?

isuruAb
  • 2,202
  • 5
  • 26
  • 39

4 Answers4

3

This is how your program should be.

public static void Main(string[] args) 
{
    DoSomething (new string[] { "I", "Like", "π" });
}

public static void DoSomething(string[] array)
{
    for (int i = 0; i < array.Length; i++)
    {
        Console.WriteLine (array [i]);
    }
}

After looking at your question and comparing it to the above one, These are the errors I've found.

  1. You cannot directly print array elements like that. It should be in a loop, for each element.

  2. You cannot create literal array like that. you will have to specify that is a new array of certain datatype.

  3. Your method is returning int which is not in the code, and also not used anywhere. you are supposed to use void in such circumstances.

Prajwal
  • 3,930
  • 5
  • 24
  • 50
1

You can either use for loop to print each element in an array or use string.join to print in one single statment as shown below. Instead of \n you can use any other delimiter. eg., if you need to print comma seperated, you can use (",",array)

public static void Main(string[] args) {
    DoSomething ({ "I", "Like", "π" });
}

public static void DoSomething(string[] array) {        
        Console.WriteLine (string.Join("\n", array); 
}
0
public static void Main(string[] args) {
    DoSomething (new[] { "I", "Like", "π" });
}

public static void DoSomething(string[] array) {
    for (int i = 0; i < array.Length; i++) {
        Console.WriteLine (array [i]);
    }
}
Backs
  • 24,430
  • 5
  • 58
  • 85
0

For your first option I would like to suggest this:

Console.WriteLine("{0} {1} {2}", new string[] { "I", "Like", "π" });

Or like this:

Console.WriteLine(String.Join(" ", new string[] { "I", "Like", "π" }));

For the second the You have to call the method like this:

 DoSomething (new[] { "I", "Like", "π" });

And you need to change the loop as well like the follwong:

for (int i = 0; i < array.Length; i++)
{
    Console.WriteLine (array [i]);
}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88