C#, default parameter value for an IntPtr
Asked Answered
P

3

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?

Prelude answered 21/10, 2012 at 15:58 Comment(0)
J
35

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)) { 
    }
Jenine answered 21/10, 2012 at 16:24 Comment(1)
Darn, I had a hunch that "default" might work, but no compiler nearby to check - so played it safe. Good answer.Copperas
C
5

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

static void SomeMethod(IntPtr? ptr = null) {
    var actualPtr = ptr ?? IntPtr.Zero;
    //...
 }
Copperas answered 21/10, 2012 at 16:8 Comment(0)
C
0

Note that using only default works as well:

void Foo(IntPtr arg = default) 
{ 
}
Censorious answered 26/3 at 19:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.