Creating and passing fixed size arrays

A

Andrus

I need to pass 9-element string array to method
I tried code below bot got a lot of compile errors.

How to fix ?

Andrus.

class Test
{
static void Main()
{
string stringarray[9];
stringarray[0] = "test";
PassArray( stringarray );
}

static void PassArray ( string p[9] ) {
// must output test
Console.WriteLine( p[0] );
}
}
 
J

Jon Skeet [C# MVP]

Andrus said:
I need to pass 9-element string array to method
I tried code below bot got a lot of compile errors.

How to fix ?

You can't. There's no way to force (at the method declaration side) an
array parameter to have 9 elements. Heck, we can't even force
parameters to be non-null, let alone fancy stuff...

Just put a test at the start of the method, and throw an
ArgumentException where appropriate.
 
K

KWienhold

I need to pass 9-element string array to method
I tried code below bot got a lot of compile errors.

How to fix ?

Andrus.

class Test
{
    static void Main()
    {
        string stringarray[9];
        stringarray[0] = "test";
        PassArray( stringarray );
    }

    static void PassArray ( string p[9] ) {
      // must output test
      Console.WriteLine( p[0] );
      }

}

In addition to what Jon said, there are also some syntactical errors
in your code, it should look more like this:

class Test
{
static void Main()
{
string[] stringarray = new string[9];
stringarray[0] = "test";
PassArray( stringarray );
}

static void PassArray ( string[] p ) {
// must output test
Console.WriteLine( p[0] );
}
}

To declare an array you put square brackets behind the type, to
instantiate it you use "new type[no_of_elements]".

hth,
Kevin Wienhold
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top