Hi geraint,
It is possible for the constructor of a base class to use the
introspection library (also known as reflection) to discover the
actual type that it is being created as, although I agree with
answerguru-ga that this "goes against the grain" of object oriented
programming.
Here's how I would do it:
using System;
using System.Reflection;
class Test
{
public static void Main()
{
BaseClass b;
b = new BaseClass();
b = new SubClass();
}
}
public class BaseClass
{
public BaseClass(){
Console.WriteLine("Hello from BaseClass Constructor");
/* here I need to know that the class "subclass" has been instantiated */
Console.WriteLine(GetType());
}
}
public class SubClass : BaseClass
{
}
I compiled and ran this program, and got the following output:
Hello from BaseClass Constructor
BaseClass
Hello from BaseClass Constructor
SubClass
As you can see, it is printing the runtime type returned by the call
to GetType(), and so we can see which type is being polymorphically
created at runtime. In your case, you could use the value returned by
the call to GetType() as the name of the file that you wish to open.
I have tested this solution using the Mono C# compiler under Linux
www.go-mono.com
but I doubt you will find any differences if you are using Microsoft tools.
Please request clarification if this answer does not yet meet your needs.
Google Search Strategy:
C# introspection type system
://www.google.com/search?q=C%23+introspection+type+system
reflection gettype
://www.google.com/search?q=reflection+gettype
system.reflection.gettype
://www.google.com/search?q=system.reflection.gettype
Regards,
eiffel-ga |