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
}
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
}
There are essentially 3 types of references in .NET
A, where A is a reference-type - a class, interface, delegate, etc)Foo*)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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With