18

I'd like to use a default parameter value of IntPtr.Zero in a function that takes an IntPtr as an argument. This is not possible as IntPtr.Zero is not a compile time constant.

Is there any way I can do what I want?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Tom Davies
  • 2,386
  • 3
  • 27
  • 44

2 Answers2

34

Somewhat unintuitive, to put it mildly, you get it by using the new operator:

    void Foo(IntPtr arg = new IntPtr()) { 
    }

That was for fun, you probably enjoy this one better:

    void Foo(IntPtr arg = default(IntPtr)) { 
    }
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
5

Since IntPtr is a struct, you could use Nullable-of-T?

static void SomeMethod(IntPtr? ptr = null) {
    var actualPtr = ptr ?? IntPtr.Zero;
    //...
 }
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900