Iirc from C, you can have a statement along these lines:
char* str = "1234";
int nonStr = *((int*)str);
(I intentionally made the string 4 characters so in the average scenario it will have the same number of bytes as the integer.) This will dereference the memory where str
is stored and give you the value if it was an integer (522207554
if I did the conversion right).
Is there any way to do the same thing in C#? I know this is a low level memory operation which is generally blissfully hidden from the C# programmer, I am only doing this for a teaching exercise.
You can do this using unsafe context and fixed
statement:
static unsafe void Main(string[] args)
{
string str = "1234";
fixed(char* strPtr = str)
{
int* nonStr = (int*)strPtr;
Console.WriteLine(*nonStr);
}
}
prints
3276849