Question

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.

Was it helpful?

Solution

You can do this using unsafe context and fixedstatement:

static unsafe void Main(string[] args)
{
    string str = "1234";
    fixed(char* strPtr = str)
    {
        int* nonStr = (int*)strPtr;
        Console.WriteLine(*nonStr);
    }
}

prints

3276849

OTHER TIPS

You're looking for the unsafe functionality of C#.

Here's one reference. A general search for "C# unsafe pointer dereference" turns up many results.

Would a union simulation be sufficient for this?

http://msdn.microsoft.com/en-us/library/acxa5b99.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top