Is there a way to pass a declared array as a parameter?

G

Guest

Give the method ProcessArray as follows:

void ProcessArray(Object [] objects)
{
foreach (Object object in objects)
{
// Do something
}
}

I can call it as follows:

Object [] ojectArray = {object1, object2, object3};
ProcessArray(objectArray);

But I would like to know if I can call it on one line by declaring the
object array in the method invocation such as:

ProcessArray({object1, object2, object3});

The compiler just doesn't like that. Any ideas?

Thanks,
 
S

SP

AAOMTim said:
Give the method ProcessArray as follows:

void ProcessArray(Object [] objects)
{
foreach (Object object in objects)
{
// Do something
}
}

I can call it as follows:

Object [] ojectArray = {object1, object2, object3};
ProcessArray(objectArray);

But I would like to know if I can call it on one line by declaring the
object array in the method invocation such as:

ProcessArray({object1, object2, object3});

The compiler just doesn't like that. Any ideas?

Use the params keyword. - void ProcessArray(params object[] list) { ... }
then you can call it like ProcessArray(object1, object2, object3);

SP


SP
 
B

Bruce Wood

Use the full-blown syntax instead of the syntactic shortcut, thus:

ProcessArray(new object[] {object1, object2, object3});
 

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