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 ?
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 ?
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.
The only available default for reference types is null (except for string which also accepts literals) as it must be available at compile time.
The easiest solution is to do it the .Net 1.1 way:
public int Insert(object o)
{
return Insert(o, new String[] { "Id" });
}
public int Insert(object o, String[] s)
{
// do stuff
}
Since this is an array why not use params
?
public int Insert(object o, params string[] ignore)
{
if (ignore == null || ignore.Length == 0)
{
ignore = new string[] { "Id" };
}
...
Then you can call it like this:
Insert(obj);
Insert(obj, "str");
Insert(obj, "str1", "str2");