c# – What is the syntax in parameter passing – "new object[] {s}"

Question:

string s= bbb.EndInvoke(ar);

BeginInvoke(new MyDelegat(PrintThat), new object[] {s});

Interested in – ,new object[] {s})
Why is s in curly braces?

Answer:

In this expression

new object[] {s}

an array of objects is created from one element, which is initialized with the string s . As a result, a reference to this array is passed as the second argument to the call to the BeginInvoke method.

BeginInvoke( new MyDelegat(PrintThat), new object[] {s} );

This is more clearly seen from the array declarations. For instance,

string s = "Hello";

object[] a = new object[] { s };
object[] a1 = new object[1] { s };
object[] a2 = { s };

Or such an array declaration and output of its elements to the console

object[] a = new object[] { "Hello", "World" };

Console.WriteLine("{0}, {1}!", a[0], a[1]);

In this case, an array will be created with two elements according to the number of initializers.

To complete the picture, you can run the following code snippet

string s = "Hello";
Console.WriteLine(new object[] { s }[0]);

The string "Hello" will be printed to the console.

Scroll to Top