0

How can I do this:

void Func(IntPtr p = IntPtr.Zero)
{
}

This is throwing an error:

Default Parameter value of 'p' must be a compile-time constant.

Since somebody marked this as a duplicate question, the other question's answer are about setting it to "default" while I wanted it to be set to IntPtr.Zero.

Thank you

stng
  • 124
  • 10
  • use the `default(IntPtr)` – Ehsan Sajjad Apr 03 '18 at 09:28
  • 1
    Note that in the latest version of C# you can declare it like so: `public static void Func(IntPtr p = default)` – Matthew Watson Apr 03 '18 at 09:29
  • But Is default(IntPtr) same as setting to IntPtr.Zero ? how can i know that? – stng Apr 03 '18 at 09:29
  • Yes, it's the same in this case. – Matthew Watson Apr 03 '18 at 09:30
  • How do you know its same? – stng Apr 03 '18 at 09:30
  • @shaarang look at source code. `Zero` is basically a field with default value. https://source.dot.net/#System.Private.CoreLib/shared/System/IntPtr.cs,d46202ed9b6005b2,references – M.kazem Akhgary Apr 03 '18 at 09:30
  • Because `(IntPtr.Zero == default)` is true. – Matthew Watson Apr 03 '18 at 09:31
  • @MatthewWatson, [7.1](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-1#default-literal-expressions) is not [latest](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/) anymore. – Sinatr Apr 03 '18 at 09:31
  • @Sinatr OK, "recent" then. :) But it's still true that will work in the latest version! – Matthew Watson Apr 03 '18 at 09:31
  • @shaarang in this special case you _can_ know it: `default` fills the struct with zeros, which happen to be the same value as `IntPtr.Zero`. But in general you are right, it is merely an implementation detail, and this may not work for other structs/values. – René Vogt Apr 03 '18 at 09:32
  • In the source code : public static readonly IntPtr Zero; Is this guaranteed to be Zero ? – stng Apr 03 '18 at 09:33
  • The general case is to use `default` and then in the implementation use `if (value == default) value = theDefaultValueYouActuallyWant`, but this of course only works if `default` isn't something you actually want to use. – Matthew Watson Apr 03 '18 at 09:34

0 Answers0