I am wondering about something which can be achieved in c++ but I want to do it in C#.
How can I pass a "pointer" to a class, from within the class that contains the code, allowing me to write code in the form of the Foo.Bar()?
namespace Example
{
public class Foo
{
MainClass MainClass;
public void Bar()
{
var somethingElse = MainClass.A.SomethingElse;
var somethingDifferent = MainClass.B.SomethingDifferent;
}
}
public class MainClass
{
public string Something;
public SubClassA A = new SubClassA(this); // <<-- not valid in c#
public SubClassB B = new SubClassB(this); // <<-- not valid in c#
}
public class SubClassA
{
private MainClass _MainClass;
public SubClassA(MainClass mainClass)
{
_MainClass = mainClass;
}
public string SomethingElse {
get {
return _MainClass.Something + " Else";
}
}
}
public class SubClassB
{
private MainClass _MainClass;
public SubClassB(MainClass mainClass)
{
_MainClass = mainClass;
}
public string SomethingDifferent
{
get
{
return _MainClass.Something + " Different";
}
}
}
}
I should state that I know I can restructure my code in a million ways to achieve a workable result, but I have a specific question I am hoping to answer! :)
Thanks
All you need to do is move the initialization expression out of the field declaration and into a constructor:
public class MainClass
{
public string Something;
public SubClassA A;
public SubClassB B;
public MainClass()
{
A = new SubClassA(this);
B = new SubClassB(this);
}
}
Note:
this
pointer during construction can be dangerous. If whatever you're calling (the constructors in this case) calls back into the object, it will be running code when you haven't finished initializing. It's a bit like calling a virtual method in a constructor - it works, but it makes the code brittle.Foo.MainClass
, so your Bar()
method is going to fail with a NullReferenceException
See more on this question at Stackoverflow