简体   繁体   中英

C#: Create and pass variable straight in the method call

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?

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 );

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");

?

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.

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

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

Do you simply mean:

MethodA("StringValue"); ??

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM