Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • C#

Idiom #225 Declare and use an optional argument

Declare an optional integer argument x to procedure f, printing out "Present" and its value if it is present, "Not present" otherwise

using System;
void f(int? x = null)
{
    Console.WriteLine(x.HasValue ? $"Present {x}" : "Not Present");
}

Optional arguments in the CLR are honoured by the calling language by substituting the specified default value in place of an omitted argument. The callee thus cannot distinguish between an omitted argument and a passed argument with the same value as the specified default. Nullable<int> is used here because int is a value type.
(defn f [& [x]]
  (if (integer? x)
    (println "Present" x)
    (println "Not present")))

Optional argument with positional parameters

New implementation...
< >
tkoenig