.net 4 string[] parameter default value setting

.net, .net-4.0, c#

Solution

The problem is that the default arguments must be constants. Here you are dynamically allocating an array. As with declaring `const` variables, for reference types only string literals and nulls are supported.

You can achieve this by using the following pattern

public int Insert(object o, string[] ignore = null)
{
  if (ignore == null) ignore = new string[] { "Id" };
  ...
  return 0;
}

Now when the caller excludes the argument at the call site, the compiler will pass the value `null` which you can then handle as required. Note that jsut to keep it simple I have modified the value of the argument in the function, not generally considered good practice but I believe this might be alright in this scenario.

Problem

I'm trying to do like this: ``` public int Insert(object o, string[] ignore = new string[] {"Id"}) ``` but it tells me that I can't do that ? why is that so ?

Original source