Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer alternative in C#

Tags:

c#

.net

pointers

I need an alternative for a C/C++-like pointer in C#, so that I can store the reference of a variable passed in a constructor. I want my local pointer to change its value every time the references value changes. Just like a pointer. But I don't want to use the real pointers in C# because they are unsafe. Is there a workaround?

    class A
    {
        public Int32 X = 10;
    }

    class B
    {
        public B(Int32 x)
        {
            Y = x;
        }

        public Int32 Y { get; set; }
    }
    static void Main(string[] args)
    {
        A a = new A();
        B b = new B(a.X);

        Console.WriteLine(b.Y); // 10
        a.X = 11;
        Console.WriteLine(b.Y); // 10, but I want it to be 11
    }
like image 390
Stefan Avatar asked Mar 11 '26 16:03

Stefan


2 Answers

Forget Pointers and start thinking in C# while coding in C# :D

I'd do something like this:

public interface IXProvider
{
     int X {get;}
}

class A : IXProvider
{
    public int X {get; set;} = 10;
}

class B
{
    public B(IXProvider x)
    {
        _x = x;
    }

    private readonly IXProvider _x;
    public int Y => _x.X;
}

static void Main(string[] args)
{
    A a = new A();
    B b = new B(a);

    Console.WriteLine(b.Y); // 10
    a.X = 11;
    Console.WriteLine(b.Y); // 11
}

Example with Bitmap: (For simplicity, assume "SomeBitmap" and "AnotherBitmap" to be actual Bitmaps)

public interface IBitmapProvider
{
     Bitmap X {get;}
}

class A : IBitmapProvider
{
    public Bitmap X {get; set;} = SomeBitmap;
}

class B
{
    public B(IBitmapProvider x)
    {
        _x = x;
    }

    private readonly IBitmapProvider _x;
    public Bitmap Y => _x.X;
}

static void Main(string[] args)
{
    A a = new A();
    B b = new B(a);

    Console.WriteLine(b.Y); // SomeBitmap
    a.X = AnotherBitmap;
    Console.WriteLine(b.Y); // AnotherBitmap
}
like image 100
Fildor Avatar answered Mar 14 '26 04:03

Fildor


There are essentially 3 types of references in .NET

  1. object references (i.e. a local/param/field of type A, where A is a reference-type - a class, interface, delegate, etc)
  2. unmanaged pointers (i.e. a local/param/field of type Foo*)
  3. managed pointers (i.e. a local/param of type ref Foo)

You (quite wisely) say you don't want to use "2", and "3" can only be used on the stack (as local variables or parameters), so that leaves "1", which is possible. For example, by passing in an A object instance instead of an int. See @Fildor's answer for a walkthrough of this.

like image 25
Marc Gravell Avatar answered Mar 14 '26 04:03

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!