Pointer Conversions (C# Programming Guide)
The following table shows the predefined implicit pointer conversions. Implicit conversions might occur in many situations, including method invoking and assignment statements.
Implicit pointer conversions
From | To |
---|---|
Any pointer type |
void* |
null |
Any pointer type |
Explicit pointer conversion is used to perform conversions, for which there is no implicit conversion, by using a cast expression. The following table shows these conversions.
Explicit pointer conversions
From | To |
---|---|
Any pointer type |
Any other pointer type |
sbyte, byte, short, ushort, int, uint, long, or ulong |
Any pointer type |
Any pointer type |
sbyte, byte, short, ushort, int, uint, long, or ulong |
Example
In the following example, a pointer to int is converted to a pointer to byte. Notice that the pointer points to the lowest addressed byte of the variable. When you successively increment the result, up to the size of int (4 bytes), you can display the remaining bytes of the variable.
// compile with: /unsafe
class ClassConvert
{
static void Main()
{
int number = 1024;
unsafe
{
// Convert to byte:
byte* p = (byte*)&number;
System.Console.Write("The 4 bytes of the integer:");
// Display the 4 bytes of the int variable:
for (int i = 0 ; i < sizeof(int) ; ++i)
{
System.Console.Write(" {0:X2}", *p);
// Increment the pointer:
p++;
}
System.Console.WriteLine();
System.Console.WriteLine("The value of the integer: {0}", number);
}
}
}
Output
The 4 bytes of the integer: 00 04 00 00
The value of the integer: 1024
See Also
Reference
Pointer Expressions (C# Programming Guide)
Pointer types (C# Programming Guide)
unsafe (C# Reference)
fixed Statement (C# Reference)
stackalloc (C# Reference)