tags:

views:

109

answers:

4

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 ?

+8  A: 

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.

Chris Taylor
yes, i do Like this ignore = ignore ?? new[] {"Id"};, why couldn't .net dev team do this o_O
Omu
@Omu, for one, because it means you can't use `null` as a real value. You can still do something similar with overloading.
Matthew Flaschen
+6  A: 

The only available default for reference types is null (except for string which also accepts literals) as it must be available at compile time.

Brian Rasmussen
+3  A: 

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
}
ck
Its called overloading...
Spence
@Spence, indeed it is...
ck
Actually it is c# 1 to 3.5 way... :)
digEmAll
A: 

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");  
Keith