Reputation: 59
I 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?
Upvotes: 0
Views: 7185
Reputation: 1464
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]);
Upvotes: 0
Reputation: 68466
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 );
Upvotes: 7
Reputation: 35594
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");
?
Upvotes: 2
Reputation: 11409
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.
Upvotes: 0
Reputation: 17612
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.
Upvotes: 0