Passing an empty array as default value of an optional parameter in C#

Rahul Kiwitech
Rahul K...
292 Points
26 Posts

Hi,

I am try to pass a optional parameter in a method/function. The optional parameter is array of string as

private Dictionary<string, string> LoadTagList(string[] skipTags = { })
{
   IRepository etRepo = new GenericRepository(_factory.ContextFactory);
   return etRepo.Get(filter: e => skipTags.Contains(e.Tag_Name)).ToDictionary(et => et.Tag_Name, et => "");
}

But it is showing compile time error as "Invalid expression {".

What will be the right way to  pass default value?

Views: 14203
Total Answered: 2
Total Marked As Answer: 0
Posted On: 26-Apr-2017 02:16

Share:   fb twitter linkedin
Answers
chkdk
chkdk
46 Points
2 Posts
         

We can't create compile-time constants of object references.

The only valid compile-time constant for reference types you can use is null, so change your code to this:

public void DoSomething(int index, string[] array = null)

And inside your method do this:

array = array ?? new ushort[0];
Posted On: 01-May-2017 02:02
NiceOne Team
NiceOne...
1390 Points
18 Posts
         

The documentation for optional arguments [https://msdn.microsoft.com/en-us/library/dd264739.aspx] says:

Each optional parameter has a default value as part of its definition. A default value must be one of the following types of expressions:

  • a constant expression;
  • an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;
  • an expression of the form default(ValType), where ValType is a value type.

Since new string[0] is neither a constant expression nor a new statement followed by a value type, it cannot be used as a default argument value.

You can try with null following

private Dictionary<string, string> LoadTagList(string[] skipTags = null)
{
  IRepository etRepo = new GenericRepository(_factory.ContextFactory);
  if (skipTags == null)
    return etRepo.Get().ToDictionary(et => et.Tag_Name, et => "");
  else
    return etRepo.Get(filter: e => !skipTags.Contains(e.Tag_Name)).ToDictionary(et => et.Tag_Name, et => "");
}
Posted On: 01-May-2017 02:49
 Log In to Chat