.net 4 string [] default parameter value

I'm trying to do like this:

public int Insert(object o, string[] ignore = new string[] {"Id"})

but he tells me that I canโ€™t do this? why is that so?

+3
source share
4 answers

The problem is that the default arguments must be constants. Here you dynamically allocate an array. As with variable declarations const, only string literals and zeros are supported for reference types.

You can achieve this using the following template.

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

, , null, . , jsut, , , , , .

+9

null ( , ), .

+6

- .Net 1.1 :

public int Insert(object o)
{
    return Insert(o, new String[] { "Id" });
}


public int Insert(object o, String[] s)
{
    // do stuff
}
+3

, params?

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

:

Insert(obj);

Insert(obj, "str");

Insert(obj, "str1", "str2");  
0

Source: https://habr.com/ru/post/1764114/


All Articles