O'Reilly logo

From Java to C#: A Developer's Guide by Heng Ngee Mok

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required