Search code examples
c#intptr

IntPtr cast vs. new


I was just looking at an example, and in it I saw the code

return new IntPtr(handle);

After poking around our code, I found that we have already used a similar pattern, but in our code we had almost the same thing:

return (IntPtr)handle;

Is there a difference between those two takes? Will the second one be "better" in any way, since it doesn't allocate new memory, or is the cast just hiding the same constructor underneath?


Solution

  • In your examples, I'm guessing handle is an integer value? IntPtr declares an explicit conversion from Int32 (int) and Int64 (long) which simply calls the same constructor:

    public static explicit operator IntPtr(int value)
    {
        return new IntPtr(value);
    }
    

    So there is effectively no difference other than possible readability concerns.