How can I add pointers as a field in a class in c#?

58 views Asked by At

I've been exploring memory optimization techniques in my C# application and came across the idea of using pointers as fields within a class to directly manipulate memory. However, I'm not entirely sure how to implement this within a class context.

Could someone guide me through the process of incorporating pointers as fields within a C# class? I'm confused about the syntax and the proper usage of pointers within a class structure.

Below is an attempt I made, but I'm aware that this isn't the correct approach. The inside of the class is wrapped in an unsafe block with a comment indicating that this is invalid and asking for guidance on the correct syntax:

public class PointerExample
{
    unsafe // This isn't valid syntax; seeking help on the correct usage
    {
        // How can I properly incorporate pointers as fields within this class?
        private int* pointerField;
    }
}

I was expecting to be able to use the pointer variable outside of the class. I tried wrapping it in an unsafe block, but it doesn't even compile.

1

There are 1 answers

0
SomeBody On

You can also use unsafe as a modifier for classes or methods. If you want to use a pointer as a field, you have to mark the whole class as unsafe:

public unsafe class PointerExample
{
   private int* pointerField;
}