29.11. Pointer casting

You can cast pointer types. Casting has to be done explicitly since pointer types are not related by a common class hierarchy. The only exception to this rule is a cast from any pointer type to void* – this can be done implicitly.

Here is an example of casting an int pointer to a long pointer type:

 1: using System;
 2:
 3: public class TestClass{
 4:
 5:   public unsafe static void Main(){
 6:     int myInt = 3;
 7:     int* pInt = &myInt;
 8:     long* pLong = (long*) pInt;
 9:
10:     long myLong = *pLong;
11:     Console.WriteLine(myLong);
12:   }
13: }

Output: [16]

[16] Output will vary.

c:\expt>test
8727635315138756611

This is a nonsensical output. Line 8 performs a pointer type cast. Casting pointers does not change the value stored in a pointer ...

Get From Java to C#: A Developer's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.