tags:

views:

83

answers:

6

enter code hereI would like to know how to declare new variable straight in the parameter brackets and pass it on like this:

MethodA(new int[]) //but how to fill the array if declared here? E.g. how to declare and set string?


MethodA(int[] Array)
...

and what if need to declare an object (class with constructor parameter)? Still possible within parameter list?

+2  A: 

You can try this:

MethodA(new int[] { 1, 2, 3, 4, 5 });

This way you achieve the functionality you asked for.

There seems to be no way to declare a variable inside parameter list; however you can use some usual tricks like calling a method which creates and initializes the variable:

int[] prepareArray(int n)
{
    int[] arr = new int[n];
    for (int i = 0; i < n; i++)
        arr[i] = i;
    return arr;
}

...
MethodA(prepareArray(5));
...

With the strings, why not just use string literal:

MethodB("string value");

?

Vlad
+7  A: 
MethodA(new int[] { 1, 2, 3 }); // Gives an int array pre-populated with 1,2,3

or

MethodA(new int[3]); // Gives an int array with 3 positions

or

MethodA(new int[] {}); // Gives an empty int array

You can do the same with strings, objects, etc:

MethodB(new string[] { "Do", "Ray", "Me" });

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

If you want to pass a string through to a method, this is how you do it:

MethodD("Some string");

or

string myString = "My string";
MethodD(myString);

UPDATE: If you want to pass a class through to a method, you can do one of the following:

MethodE(new MyClass("Constructor Parameter"));

or

MyClass myClass = new MyClass("Constructor Parameter");
MethodE(myClass );
GenericTypeTea
A: 

Either new int[0] or new int {} will work for you. You can also pass in values, as in new int {1, 2, 3}. Works for lists and other collections too.

Lunivore
And how about string?
Bornemix
`new string { "cat", "dog", "horse" }` - no problem. You might also look at `params` - lets you put an arbitrary number of parameters at the end of a method, as used in string.Format amongst others: `public Thing DoMyThing(Thing aThing, params string[] moreArgs)`
Lunivore
Or, using your example: `MethodA(params int[] values)` could be called by `MyClass.MethodA(1, 2, 3, 4, 5)`
Lunivore
A: 

In your case you would want to declare MethodB(string[] strArray) and call it as MethodB(new string[] {"str1", "str2", "str3" })

P.S. I would recomment that you start with a C# tutorial, for example this one.

Ando
A: 

Do you simply mean:

MethodA("StringValue"); ??

w69rdy
A: 

As a side note: if you add the params keyword, you can simply specify multiple parameters and they will be wrapped into an array automatically:

void PrintNumbers(params int[] nums)
{
    foreach (int num in nums) Console.WriteLine(num.ToString());
}

Which can then be called as:

PrintNumbers(1, 2, 3, 4); // Automatically creates an array.
PrintNumbers(new int[] { 1, 2, 3, 4 });
PrintNumbers(new int[4]);
Gnafoo