Suppose you have two classes, as in the example below.
How would you modify SplitObject such that it always returns an object of type t, such as in Main(), where it should return an object of type DerivedClass?
I’m guessing the solution would involve reflection? I haven’t learned anything about reflection yet, so I don’t know how this would work.
public class BaseClass
{
float _foo;
public BaseClass(float foo){_foo = foo}
public BaseClass SplitObject()
{
Type t = GetType();
// Do something with t
_foo = _foo/2f;
return new BaseClass(_foo); // I want to construct an
// object of type t instead
// of type BaseClass
}
}
public class DerivedClass : BaseClass
{
public DerivedClass(float foo) : base(foo){}
}
class Program
{
static void Main()
{
BaseClass foo = new DerivedClass(1f);
BaseClass bar = foo.SplitObject(); // should return a DerivedObject
}
}
If you really wanted to use reflection, you could do something like:
Of course, there is now an implicit contract that all derived classes must implement such a constructor. Unfortunately, such contracts cannot be specified in the current type-system; so violations will not be caught at compile-time. It would be much better to go with erash’s idea. I would do something like: