Question

Having the code below, why is the variable declaration considered as correct syntax, but not also the method call?

public static void Func(string[] p)
{
}

public static void Test()
{
    string[] a = { "x", "y", "z" };
    Func({"x", "y", "z"});
}
Was it helpful?

Solution

It looks like everybody else is focusing on the workaround (which is simply to specify that you need a new [] { "some", "strings" }. The why is a little less obvious though.

The former is valid because the compiler knows to use your initialization syntax to create an Array (because you've defined it as such).

The later would have some issues. It may seem trivial in this case because the compiler should, theoretically, be able to figure out that you need a string[]. Think about cases where you have a Func<IEnumerable<string>> though. What type gets generated in that case? Would the compiler take a wild-ass guess? Always use an Array (even though there might be a better fit)? It could be one of a number of possibilities.

I'm guessing that's the reason that the language specification doesn't allow for passing things this way.

OTHER TIPS

You need to pass in a value as the argument. {"x", "y", "z"} is not a value. It can be used as short-hand for initializing a variable.

Note that both of these are valid:

List<string> a = new List<string>() {"x", "y", "z"};
string[] b = new string[] {"x", "y", "z"};

And the full version of what it represents:

List<string> a = new List<string>();
a.Add("x");
a.Add("y");
a.Add("z");

So you need to make an object (new)

new [] {"x", "y", "z"}

Or make an object beforehand and pass that in.

As for why this is like this, you need to pass in a value, not a helper for array initialization.

You can initialize the object directly on the inside of the method call, but do not think a good practice.

where you used:

 

Func ({"x", "y", "z"}); 

The above form you tried to pass an object not instantiated, ie it does not already exist on your "context". The correct is you initialize it to be generated in a reference memory to this value and thus the "Func" method you can use it.

In the case of variable declaration:

string[] a = {"x", "y", "z"}; 

In this case your compiler is reading:

string[] a = new string[] {"x", "y", "z"};

It does this interpretation alone, without requiring you to do object initialization explicitly.

So my answer is best for this situation you must first create the object then pass it as a parameter to the method:  

  string[] a = {"x", "y", "z"}; 
  Func (s);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top