Specify optional arguments for structure arguments

Page updated :

Optional arguments allow you to give an initial value to an argument without overloading a method with a different number of arguments.

However, only constants such as "10", "Sample" and "null" can be specified as optional arguments, and you cannot specify a value that was created in new or defined by static readonly that is determined when the program runs.

The same is true if the structure is an argument. For example, if the type is IntPtr, you cannot specify IntPtr.Zero as the initial value. It cannot specify 0, and it cannot be null because it is a structure. (Nullable allows you to specify null, but excludes because the type of the argument changes.)

You can use "default(T) to use the structure as an optional argument.) This is equivalent to the value created with new T().

public void DoAction(IntPtr handle = default(IntPtr))
{
  // 処理
}

You can only specify 0 or null for each value in the structure, so overload the method if you want to give an initial value separately.