I’m trying to make a class Bar that extends a class Foo. The code of Foo is beyond my control.
When someone makes a new instance of Bar (by writing something like Bar x = new Bar();) I want this to trigger a call to the Foo constructor that takes an input argument.
Basically:
class Foo {
public Foo(string message) { print("The new Foo says: " + message); }
}
class Bar : Foo {
public Bar() : base(this.GetType()) { }
}
So when someone uses new Bar(), it should print out The new Foo says: Bar. (Assuming there’s a print function, which isn’t the point here.)
Instead, C# complains because I’m trying to compute a result in the arguments to the base constructor.
Remember, Foo is beyond my reach, so I can’t change any code in Foo.
You can’t use
thisbefore the actual constructor of a class, as only the parameters and static members (as thestaticconstructor is run before any non-static ones) are accessable in that context. The runtime first needs to construct any classes you inherit from before you are able to accessthis.As a workaround, you can use the
typeofoperator:Of course, this isn’t portable, but is probably the best thing you’ll be able to come up with.