[Mono-list] Default Arguments

Brian Crowell brian@fluggo.com
Fri, 3 May 2002 19:50:48 -0500


> I _think_ you should be able to do this in C#:
>
>    void Add(
>       object Item,
>       [Optional] string Key,
>       [Optional,DefaultValue(null)] object Value
>    )
>
> The OptionalAttribute class is part of System.Runtime.InteropServices; the

System.Runtime.InteropServices.OptionalAttribute has a disclaimer in the
documentation that says not all languages support optional parameters. So
while this would be the correct way to mark the parameter so that it would
be optional in VB.NET, it would still not be optional in C#, since C# does
not support optional parameters.


> DefaultValueAttribute class is part of System.ComponentModel
> (which makes me
> wonder whether that's right, because it would seem to be implying
> that it's
> used for COM clients, not native .NET clients).

The System.ComponentModel namespace has nothing to do with COM; it is more
for design surfaces, such as the ones in VS.NET. Specifically, the
DefaultValueAttribute has to do with what value of a property is considered
the "default;" if the property is not explicitly set in the code for a
designable class (such as a form), VS.NET displays the value from this
attribute in the Properties palette. There are other uses, too. This
attribute has no effect on run-time behavior.

It's dangerous to mix and match classes from different namespaces without
careful forethought! Also, remember that attributes only mean something to a
program that is looking for them.


Anyhow, to answer your question, Chris, in C# the method is usually set up
like this:

  void Add( object Item ) {
    Add( Item, String.Empty /* or null */, null, null );
  }

  void Add( object Item, string Key ) {
    Add( Item, Key, null, null );
  }

  void Add( object Item, string Key, object Before ) {
    Add( Item, Key, Before, null );
  }

  void Add( object Item, string Key, object Before, object After )
  {
     // Actual method code....
  }

After a while, you learn to create fewer optional-parameter methods  :P

--Brian




---