NetInverse Developers Blog

March 7, 2009
Category: .Net — Tags: , — admin @ 10:32 pm

  Can you get the address of a Managed Type? look at the code below:

    
    class Point
    {
        public int x;
        public int y;  
    }
  
    class A  
    {
        unsafe static void Main()   
        {
            Point pt = new Point();
            // Using fixed allows the address of pt members to be
            // taken, and "pins" pt so it isn't relocated.
            fixed (int* p = &pt.x) //This is okay!
            {
                *p = 1;
            }

            fixed (int* p = &pt) //This won't compile.  
            {

                //...
            }  
        }
    }

 Above code won’t compile due to following error:

Cannot take the address of, get the size of, or declare a pointer to
a managed type ('something.Point')

Conclusion: from above sample, you can see that you cannot get the address of a managed type!  But you can point to value types of a class.

By the way, you might don’t know much about fixed statement, I copied the definition of it from MSDN.

fixed Statement (C# Reference)

The fixed statement prevents the garbage collector from relocating a movable variable. The fixed statement is only permitted in an unsafe context.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

©2009 NetInverse. All rights reserved. Powered by WordPress