Question

I'm trying to convert C++ code into C#. We have functions that accept pointers in C++. In C# we are having troubles doing it. We have tried the following demo code:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Test obj = new Test();
            int a,b;
            Console.WriteLine("Initial Values");
            a = 20;
            b = 100;
            obj.SetRef(ref a,ref b);
            Console.WriteLine("Value of A: " + a);
            Console.WriteLine("Value of B: " + b);
            obj.SetValRef(ref a);
            Console.WriteLine("After Ref");
            Console.WriteLine("Value of A: " + a);
            Console.WriteLine("Value of B: " + b);
            Console.ReadKey();
        }   
    }



    class Test
    {

        public void SetRef(ref int x, ref int y)
        {
            y = x;
        }

        public void SetValOut(out int x)
        {
            x = 10;

        }

        public void SetValRef(ref int x)
        {
            x = 10;

        }
    }
}

When we run it the output is

Initial Values
Value of A: 20
Value of B: 20
After Ref
Value of A: 10
Value of B: 20

We want that if value of one variable is changed then the value of second should automatically change( pointers).

Was it helpful?

Solution

The only way to do that in C#/.NET is to use unsafe code and to declare one of the variables as a pointer.

However, this is not good advice for C# code. I would highly consider restructuring the code to be more C#-like or you're going to fight the language a lot.

Or, a better advice, how about compiling the code with the managed C++ compiler and wrapping it up in some nice real managed types instead of going through the hassle of porting?

Anyway, here's a LINQPad example, however, that shows what to do if you really must port it and need that ability:

void Main()
{
    unsafe
    {
        int x = 10;
        int* y = &x;

        Debug.WriteLine("x=" + x + ", y=" + *y);

        ChangeValue(ref x);

        Debug.WriteLine("x=" + x + ", y=" + *y);

        ChangeValue(ref *y);

        Debug.WriteLine("x=" + x + ", y=" + *y);
    }
}

static void ChangeValue(ref int value)
{
    value += 10;
}

This will output:

x=10, y=10
x=20, y=20
x=30, y=30

OTHER TIPS

You can use a 'pointer' on c#

using 'unsafe' keyword, and change compiler option to allow unsafe code

'ref' is not fit for it

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