One of the biggest advantages of managed frameworks/platforms like Microsoft’s .NET Framework (and it’s Linux-counterpart, Mono), and Java is that you, as a developer, have a choice of not mucking around with pointers. To be totally honest, with Java you’re forced not to – in C#, it’s a choice you have to make.
There’s plenty of good reasons for not using (unsafe!!) pointers, but that’s not the issue here. The question is, what if you want something to “point” to another object, and synchronize it’s value automatically, without resorting to unsafe pointers? There’s actually a quite simple answer using just a single line of C# code.
Whereas in C++ you could write something like what appears below, in C# you’d have to declare it as unsafe, then jump through a hundred hoops to get it to properly point to a managed object:
[sourcecode language=’cpp’]CustomObject *myP;
myP = &originalObject;
*myP = Some_Value;[/sourcecode]
You might think it’s impossible to write such code in C# without worrying about unsafe expressions, nullifying the benefits of the GC, and a bunch of other things – but it’s not. In C#, code like this can do the trick of pointing one item to another – but with a catch:
[sourcecode language=’csharp’]MyDataSet.DvdsRow CurrentItem
myObject = value;
Looking at the code, the catch should be glaringly obvious: you must hard-code the object you’re pointing to! While the above code can be used to bypass the double-casting (a must when dealing with ADO.NET binding sources), you’ll need one property per binding source, which is a major constraint.
You shouldn’t think of this as a pointer so much as it is an alias – but to an item/object instead of a namespace or class. It can help you bypass complex castings or long object names (that need to be kept in-sync with the original!), but isn’t really a pointer in that you can’t change the object it points to; a single-use pointer, if you will.
Technically, there is a workaround. By using the immensely-difficult and often-misused on-the-fly compilation features of C#/VB.NET you can actually create a class “managedPointer” that contains the above code in addition to a function to change the object it points to, but we’re not going to be getting into that here – nevertheless, it’s doable.