8

The below code would be quite cool if it worked. However, I can't get it to compile, so I'm assuming this isn't going to work in any form?

public void foo(char[] bar = new char[]{'a'})
{
}

The next-best option is to just do

public void foo(char[] bar = null)
{
   if (bar==null)
      bar = new {'a'};
}
nneonneo
  • 171,345
  • 36
  • 312
  • 383
maxp
  • 24,209
  • 39
  • 123
  • 201

5 Answers5

6

No it's not possible. The default value needs to be a compile-time constant. The default value will be inserted into the caller, not the callee. Your code would be a problem if the caller has no access to the methods used to create your default value.

But you can use simple overloads:

public void foo(char[] bar)
{
}

public void foo()
{
  foo(new char[]{'a'});
}
CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
1

No, because optional parameter default values need to be constant.

Why do optional parameters in C# 4.0 require compile-time constants?

Community
  • 1
  • 1
Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187
1

That will never work because char[] is not a value type but rather a reference type. Only value types can have constants assigned to them in optional parameters. You cannot have a reference to an object (such as an array) at compile time. (Null is the only valid value for an optional reference type.)

Paul Sasik
  • 79,492
  • 20
  • 149
  • 189
  • 1
    A nitpick: Strings are reference types, and `void M(string s = "hello") {}` is perfectly legal! – LukeH Mar 22 '11 at 13:14
  • @LukeH: That is true but .NET's architects have gone to some lengths to disguise that fact and made the string behave like a value type. string is definitely an exception in a variety of .NET concepts. – Paul Sasik Mar 22 '11 at 13:19
1

only with value types you have the possibility to set the default value of a parameter to compile-time constants (making it optional). For reference types, only strings have that ability. Other types can only be set to null.

edit: thanks @Martinho Fernandes for pointing that out. For value types, only compile-time constants are allowed

AbdouMoumen
  • 3,814
  • 1
  • 19
  • 28
  • 2
    This assertion about value types is false. `void foo(DateTime x = new DateTime(2011,3,22)){}` fails to compile. What you can use is *compile-time constants*. – R. Martinho Fernandes Mar 22 '11 at 13:04
1

Other comments apply as well, but also consider that, since the default value is inserted into the caller at compile time, changing the default value at some later date will not change the value in the caller code (assuming it's being called from another assembly.) Because of this, what you propose as a work-around, or next-best option, is in fact a better practice.

Charles Bretana
  • 143,358
  • 22
  • 150
  • 216