Call (static) method from child clases - c#

I've created an abstract class, lets call it FooBarizable, that is the parent of 2 clases(more in the practice), Foo and Bar. Now, I have a FooBarizableManager that manages Foo and Bar classes, depending on his type. And from this FroobarizableManager, I want to call getFooBarizables(). Let's see the structure:
FooBarizable.cs:
public abstract class FooBarizable{
public string Name { get; set; }
public static IEnumerable<FooBarizable> GetFooBars(){
throw new NotImplementedException();
}
}
Foo.cs:
public class Foo : FooBarizable{
public static IEnumerable<FooBarizable> GetFooBars(){
return API.getFoos();
}
}
Bar.cs:
public class Bar : FooBarizable{
public static IEnumerable<FooBarizable> GetFooBars(){
return API.getBars();
}
}
FooBarizableManager.cs:
public class FooBarizableManager {
private Type type;
public FooBarizableManager(Type _t){
this.type = _t;
}
public void showFooBarizables(){
MethodInfo method = type.GetMethod("GetFooBars");
IEnumerable<FooBarizable> FooBars = (IEnumerable<FooBarizable>)method.invoke(null, null);
show(FooBars);
}
...
}
So, my problem is that I want to get the object collection from the manager, using the type, but enforce child classes to implement getFooBars() method.
Problems I've faced:
.Net does not allow to define static abstract methods, so I cannot create public static abstract IEnumerable<FooBarizable> GetFooBars() and enforce child class to implement it.
The way that is implemented does not enforce the implementation of the method in child classes, but I try to at least throw a NotImplementedException. The problem is that when I call MethodInfo method = type.GetMethod("GetFooBars"); in the manager, if the subclase does not implements the method, method is null, and NullPointerExceptionis called instead.
I've tried to create an instance method instead of static a static one, it solves the enforce problem because child classes have to implement it, But it does not seem correct to me to create an unnecessary instance to call a method.
So, is there any solution to enforce child classes to implement getFooBar() method? if not, how can I throw the NotImplementedException instead of NullPointerException?

is there any solution to enforce child classes to implement getFooBar() method?
Not for static methods. Static methods are tied to the specific class, so they can't be inherited, nor abstract or virtual.
If you want to make the method polymorphic it needs to be an instance method.
how can I throw the NotImplementedException instead of NullPointerException
The result you're getting that exception is because the type does not have a GetFooBars method, so method is null. So you could check for null first:
public void showFooBarizables(){
MethodInfo method = type.GetMethod("GetFooBars");
if(method == null)
throw new NotImplementedException();
IEnumerable<FooBarizable> FooBars = (IEnumerable<FooBarizable>)method.invoke(null, null);
show(FooBars);
}
But throwing that exception is a little misleading because it may seem to the caller that the showFooBarizables method is not implemented, not the underlying GetFooBars.
Since these method seem to be factory methods, perhaps you need a factory for each type instead? It seems like you are trying to use generics as a replacement for overloads. Factory methods generally aren't generic since they have to have different logic for each type. You could create a "base" factory that contains common code, then sub-class the factory for each specific type.

Of course .NET doesn't allow you to write virtual static methods :)
The whole point of virtual methods is that when you call the Base.DoSomething method on an instance of type Derived, it's the code in Derived.DoSomething that executes. But that means you need the instance to know its actual runtime type, so that you know what method is really supposed to be executed.
A typical alternative is to use some form of a factory interface. That is, instead of querying Foo.GetFooBars or Bar.GetFooBars, you'll get an instance of a provider of the relevant instance type, e.g. Fooizer.GetFooBars and Barizer.GetFooBars, where both Fooizer and Barizer implement IFooBarProvider. GetFooBars doesn't fit into the FooBarizable interface - because that's not where it belongs. Object-oriented design, responsibility, substitution principles and all that :)
Then, if you need to enforce the implementation in code (e.g. to make sure someone doesn't forget to implement the proper provider), you could make an abstract instance method or property on your type:
public abstract class FooBarizable
{
protected abstract IFooBarProvider GetDefaultProvider();
}
Depending on what you're actually trying to do, it might make sense to make those classes generic. Or not :)

You cannot force child classes to define a static methods. As you noted, abstract methods cannot be static, and interfaces work with instances only. I think you are trying to put too much into a single class. It looks like your trying to create some franken-factory. Instead just separate the factory functionality and the abstract parent object.
public abstract class FooBarizable {
public string Name { get; set; }
}
Factory example:
public static class FooBarizableFactory {
public static IEnumerable<FooBarizable> GetFooBars(Type type){
var parentType = typeof(FooBarizable);
if (!parentType.IsAssignableFrom(type))
throw new ArgumentException("Not a FooBarizable");
switch(type.Name) {
case "Foo":
return new List<Foo>() { new Foo () };
case "Bar":
return new List<Bar>() { new Bar() };
default:
throw new ArgumentException("Not a known FooBarizable");
}
}
}
Usage:
var fooBars = FooBarizableFactory.GetFooBars(typeof(Foo));
Demo of idea.

.Net does not allow to define static abstract methods
Because C# compiler makes static as abstract and sealed. So you can't make it just abstract or sealed.
The problem is that when I call MethodInfo method =
type.GetMethod("GetFooBars"); in the manager, if the subclase does not
implements the method, method is null, and NullPointerExceptionis
called instead.
I said static is abstract and sealed. So because of it's sealed derived class will not have GetFooBars method.
You can use the BindingFlags.FlattenHierarchy flag. That way it will check also protected and public static classes of base classes. If It's not implemented on derived class it will check base class. So in your stiuation base class GetFooBars will called, if the derived one does not have this method.

There's no way to enforce static methods via any form of inheritance or polymorphism, but a potential workaround would be to implement an extension method(s) for FooBarizable, so that any class that inherits it will have access to the extension.

Static methods are not related to the object (instance) of the class, it is always related to the class itself.
One way to enforce the implementation of a method would be the use of an interface.
Another way, and this is what I think you want, since this method will have different behavior in different instances, would be the use of abstract methods.
public abstract class AbstractClass
{
public abstract int MustIMplementThis(string param1);
}
public class ChildClass : AbstractClass
{
public override int MustIMplementThis(string param1)
{
throw new NotImplementedException();
}
}
All classes that inherits from AbstracClass will have to implement the methods listed on the parent class.

Related

Why calling method on interface uses base implementation instead of override?

I have a problem with my code.
I would expect that since I'm constructing the Implementation object; every time I call Method() I'd use actual Implementation.Method() and not it's abstract's Base.Method(). It does not seem reasonable that I have to downcast to actual implementer or specify interface explicitly (So interfaces are not transitive in C#? I will call the "first proper instance of interface implementer" and not my class?)
I have a structure similar to this (simplified for clarity):
https://dotnetfiddle.net/oYVlQO
using System;
public interface IBase
{
string Method();
}
public abstract class Base : IBase
{
public string Method() { return "Sample"; }
}
public class Implementation : Base // if I add ", IBase" to this it works as expected, but why?
{
new public string Method() { return "Overriden"; }
}
public class Program
{
// and it's used like so...
public static void Main()
{
IBase b = new Implementation();
//Implementation b = new Implementation(); // It works as expected, always using Implementation.Method();
Console.WriteLine(b.Method()); // Produces "Sample", so Base.Method(). Why not implementation?
Console.WriteLine(((Implementation) b).Method()); // Produces "Overriden", so Implementation.Method(); Since when I have to downcast to use overriden method!?
}
}
}
I'm really scratching my head over this; Especially that the same code in Java works "as I would expect" https://repl.it/repls/VitalSpiritedWebpage
I've tried to find it in the c# specs to no avail, maybe I do not have the proper keywords...
In cause of the question, which is:
Why is it that way?
My answer:
Because you don’t override the method but hide it.
The interface is implemented by the baseclass, so the Method is called on the base-class.
To answer the question, which isn’t asked:
How would it work?
Answer:
using System;
public interface IBase
{
string Method();
}
public abstract class Base : IBase
{
public virtual string Method() { return "Sample"; }
}
public class Implementation : Base
{
public override string Method() { return "Overriden"; }
}
You may want to take a look at the part of the C# spec that deals with interface re-implementation.
When you access a member through the interface, it begins its lookup at the most derived type that explicitly implements that interface. In your example, the most derived type is Base and so it calls the method that's present there.
When you added IBase to the list of interfaces explicitly implemented by Implementation it worked, because that's the new starting point for lookup and it finds your new method.
You can either solve your problem by making the base member virtual and then overriding it in derived classes, or you can re-implement the interface by including that in the list for your Implementation class.
So the problem in my sample code is two-fold.
I assumed that in C# methods are "virtual" by default (as is in Java). Since I'm usually coding in Java, I've made an incorrect assumption.
See Is it possible to override a non-virtual method?
If I'd use virtual, I could override the method and achieve exactly the output I expected, as described in doc:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/virtual namely "When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member."
My code, hovewer, is using method hiding, so unless I inform the compiler about my intention of using my implementation, it'll default to non-hidden method (as resolved by abstract class being the actual, original implementer)

How do I write an interface or abstract class that specifies creation logic?

I have a generic class that deals with widgets that can be deserialized from strings. Instances of the generic class will take the type of one of these widgets as a template parameter, and then create these widgets from strings. I wish to use the covariance properties of C#'s generics to write code like WidgetUser<IWidget> to deal with objects that may be WidgetUser<RedWidget> or WidgetUser<BlueWidget>. The problem is that to create a widget from a string inside of WidgetUser<T>, I'm forced to add new() as a guard. This makes WidgetUser<IWidget> an invalid type. Currently, I have code like this:
interface IWidget
{
// Makes this widget into a copy of the serializedWidget
void Deserialize(string serializedWidget);
}
class WidgetUser<T> where T : IWidget, new()
{
public void MakeAndUse(string serializedWidget)
{
var widget = new T();
widget.Deserialize(serializedWidget);
Use(widget);
}
}
With this code, I can make WidgetUser<BlueWidget> just fine, because BigWidget satisfies new(). I cannot write WidgetUser<IWidget> because instances of IWidget (or an equivalent abstract class) are not guaranteed to work with new(). A workaround could be this:
abstract class WidgetUser
{
public abstract void MakeAndUse();
}
class WidgetUser<T> : WidgetUser
where T : IWidget, new()
{
/* same as before but with an 'override' on MakeAndUse */
}
With this code, I can create a WidgetUser<BlueWidget> then write code that deals with just WidgetUser. I could have similar code with an abstract class BaseWidget instead of IWidget that accomplishes almost the same thing. This is functional, but I suspect there is a more direct approach that doesn't force me to define a dummy class. How can I convey my intent to the type system without creating dummy classes or extra factories. I just want an interface that says "you can make one of these from a string".
TL;DR:
Is there some way to write an interface or abstract class that lets me create an instance from a string but doesn't require me to have new() as a guard on WidgetUser<T>?
The problem here is that your Deserialize() method should be a static method. Therefore it should not be a member of IWidget itself - it should be a member of a factory interface, or it should be a static member of a concrete Widget class which is called from a concrete factory method. I show the latter approach below.
(Alternatively, you could use a Func<IWidget> delegate to specify it, but it's more usual to provide a full factory interface.)
So I suggest you create the factory interface:
interface IWidgetFactory
{
IWidget Create(string serialisedWidget);
}
Then remove the Deserialize() from IWidget:
interface IWidget
{
// .. Whatever
}
Then add a static Deserialize() method to each concrete implementation of IWidget:
class MyWidget: IWidget
{
public static MyWidget Deserialize(string serializedWidget)
{
// .. Whatever you need to deserialise into myDeserializedObject
return myDeserializedObject;
}
// ... Any needed IWidget-implementing methods and properties.
}
Then implement the factory for your concrete widget class using the static Deserialize() method from the concrete widget class:
sealed class MyWidgetFactory : IWidgetFactory
{
public IWidget Create(string serialisedWidget)
{
return MyWidget.Deserialize(serialisedWidget);
}
}
Then add a constructor to your WidgetUser class which accepts an IWidgetFactory and use it in MakeAndUse():
class WidgetUser
{
public WidgetUser(IWidgetFactory widgetFactory)
{
this.widgetFactory = widgetFactory;
}
public void MakeAndUse(string serializedWidget)
{
var widget = widgetFactory.Create(serializedWidget);
Use(widget);
}
private readonly IWidgetFactory widgetFactory;
}
Note that in this scenario, you no longer need the type argument for WidgetUser, so I have removed it.
Then when you create the WidgetUser you must supply a factory:
var widgetUser = new WidgetUser(new MyWidgetFactory());
...
widgetUser.MakeAndUse("MySerializedWidget1");
widgetUser.MakeAndUse("MySerializedWidget2");
Passing in a factory allows a lot more flexibility.
For example, imagine that your serialization scheme included a way of telling from the serialized string which kind of widget it is. For the purposes of simplicity, assume that it starts with "[MyWidget]" if it's a MyWidget and starts with ["MyOtherWidget"] if it's a MyOtherWidget.
Then you could implement a factory that works as a "virtual constructor" that can create any kind of Widget given a serialization string as follows:
sealed class GeneralWidgetFactory: IWidgetFactory
{
public IWidget Create(string serialisedWidget)
{
if (serialisedWidget.StartsWith("[MyWidget]"))
return myWidgetFactory.Create(serialisedWidget);
else if (serialisedWidget.StartsWith("[MyOtherWidget]"))
return myOtherWidgetFactory.Create(serialisedWidget);
else
throw new InvalidOperationException("Don't know how to deserialize a widget from: " + serialisedWidget);
}
readonly MyWidgetFactory myWidgetFactory = new MyWidgetFactory();
readonly MyOtherWidgetFactory myOtherWidgetFactory = new MyOtherWidgetFactory();
}
Note that this is generally not the best way to do things - you are better using a Dependency Container such as Autofac to manage this kind of thing.
I would implement WidgetFactory and call WidgetFactory.Create<T>(serializedWidget) to avoid the usage of new T()

How to define virtual method with return type which is not void in C#

This might sound like a dumb question, but I need to write a virtual method that is being overridden by inherited class. I don't need the virtual method to have any code, since this method is fully dependent on inherited class, therefore all code will be in the override methods.
However, the method has a return type that is not void. If I keep the virtual method empty it would give me an error "no all path return a value".
The only solution I came up with was to implement the virtual method with returning a dummy empty string, but I don't feel this is the best way. Is there any other way to define a virtual method with return type?
Edit:
Even most answers were correct in their own way, they did not help in my case, therefore I am adding snippets of the code which shows why I need to create instance of the base class, and why I can't use interface, or abstract:
//base class
public class Parser
{
public virtual string GetTitle()
{
return "";
}
}
//sub class
public class XYZSite : Parser
{
public override string GetTitle()
{
//do something
return title;
}
}
// in my code I am trying to create a dynamic object
Parser siteObj = new Parser();
string site = "xyz";
switch (site)
{
case "abc":
feedUrl = "www.abc.com/rss";
siteObj = new ABCSite();
break;
case "xyz":
feedUrl = "www.xzy.com/rss";
siteObj = new XYZSite();
break;
}
//further work with siteObj, this is why I wanted to initialize it with base class,
//therefore it won't break no matter what inherited class it was
siteObj.GetTitle();
I know the way I cast Parser object to Site object doesn't seem very optimal, but this is the only way it worked for me, so Please feel free to correct any thing you find wrong in my code.
Edit (Solution)
I followed the advice of many of replies by using interface and abstract. However it only worked for me when I changed the base class to abstract along with all its methods, and inherited the base class from the interface, and then inherited the sub classes from the base class. That way only I could make sure that all classes have the same methods, which can help me generate variant object in runtime.
Public interface IParser
{
string GetTitle();
}
Public abstract class Parser : IParser
{
public abstract string GetTitle();
}
Public class XYZ : Parser
{
public string GetTitle();
{
//actual get title code goes here
}
}
//in my web form I declare the object as follows
IParser siteObj = null;
...
//depending on a certain condition I cast the object to specific sub class
siteObj = new XYZ();
...
//only now I can use GetTitle method regardless of type of object
siteObj.GetTitle();
I am giving the credit to CarbineCoder since he was the one who put enough effort to take me the closest to the right solution. Yet I thank everyone for the contribution.
You can throw NotImplementedException instead of returning object:
public virtual object Method()
{
throw new NotImplementedException();
}
But if you are not implementing anything in virtual method you can create abstract instead of virtual:
public abstract object Method();
Edit:
Another option is to create interface for it.
public interface IMethods
{
object Method();
}
And make your classes children of this interface.
you need to use abstract here. The abstract modifier indicates that the thing being modified has a missing or incomplete implementation.
public abstract returntype MethodName();
But as you say, 'since this method is fully dependent on inherited class, therefore all code will be in the override methods', than if you are really going to override the functionality of the method in inherited class, why do you care if the method returns dummy or stuff? (e.g: you can make it virtual and get going)
Edit: as you cannot mark class as abstract, you can use virtual method instead.
public virtual returntype MethodName()
{
.....
return xyz;
}
(just for info: An abstract member is implicitly virtual. and abstract is sort of pure virtual. so you need virtual, instead of pure virtual)
Since other answers have discussed about abstract/virtual implementation, I am suggesting my own version.
There is a contradiction in your requirement.
You want a base class which is not an abstract but it has a method which is not implemented. Don't you think this unimplemented method will make the class incomplete and end up making it an abstract one even though you haven't explicitly said so?
So lets assume your class will never be an abstract class and its perfectly reasonable to have it as a normal class. Does it make sense to remove this method from the class altogether and move it to an interface?
Can you try extracting this method and put it into an interface.
interface NewInterface
{
string NewMethod();
}
public BaseClass
{
...
}
public DerivedClass : BaseClass, NewInterface
{
public string NewMethod
{
...
}
}
If you can do this, then you need not have to worry about the base class being abstract/ having NotImplemented exception, only downside is every derived class should implement this interface, but thats the point of making the base class non-abstract.
I don't see any problem in implementing Abstract BaseClass/ Interface for your approach. Both are supposed to be the solution for your problem.
//Parser siteObj = new Parser(); - Dont initialize it here,
//your are initializing it once more below
NewIterface siteObj;
string site = "xyz";
switch (site)
{
case "abc":
feedUrl = "www.abc.com/rss";
siteObj = new ABCSite();
break;
case "xyz":
feedUrl = "www.xzy.com/rss";
siteObj = new XYZSite();
break;
}

What's the difference between an abstract class, and a class with only protected constructors? (.NET)

What are all the difference between an abstract class, and a class with only protected constructor(s)? They seem to be pretty similar to me, in that you can't instantiate either one.
EDIT:
How would you create an instance in a derived class, with a base class with a protected constructor? For instance:
public class ProtectedConstructor
{
protected ProtectedConstructor()
{
}
public static ProtectedConstructor GetInstance()
{
return new ProtectedConstructor(); // this is fine
}
}
public class DerivedClass : ProtectedConstructor
{
public void createInstance()
{
ProtectedConstructor p = new ProtectedConstructor(); // doesn't compile
}
public static ProtectedConstructor getInstance()
{
return new ProtectedConstructor(); // doesn't compile
}
}
You can instantiate a class with protected constructors from within the class itself - in a static constructor or static method. This can be used to implement a singleton, or a factory-type thing.
An abstract class cannot be instantiated at all - the intent is that one or more child classes will complete the implementation, and those classes will get instantiated
Edit:
if you call ProtectedConstructor.GetInstance(); instead of new ProtectedConstructor();, it works. Maybe protected constructors can't be called this way? But protected methods certainly can.
Here is an interesting article on the topic.
Most of the time, there is little practical difference, as both are only able to be generated via a subclass.
However, marking a class abstract has two benefits:
With protected constructors, it's still possible to create an instance of the class in two ways. You can use Activator.CreateInstance with BindingFlags.NonPublic, or you can use a factory method defined in the class (or a subclass) to create an instance of the class. A class marked abstract, however, cannot be created.
You are making your intention more clear by marking the class abstract. Personally, I find this the most compelling reason to do so.
From an outside , black-box perspective, yes they are similar in that you cannot instantiate either one. However, you can never instantiate an abstract class, where you can construct a class with only protected constructors from within the class itself, or from an inheritor.
An abstract class can have abstract methods; methods that consist only of the method signature, but no body, that child classes must implement.
Seriously, not one person mentioned that yet?
Your example is flawed because in the getInstance case because you construct a ProtectedConstructor class and expect to down cast it as a DerivedClass. Instead you need a slightly more complete implementation where the derived class has a constrcutor:
public class ProtectedConstructor
{
protected ProtectedConstructor(string arg)
{
// do something with arg
}
public static ProtectedConstructor GetInstance()
{
return new ProtectedConstructor("test");
}
}
public class DerivedClass : ProtectedConstructor
{
protected DerivedClass(string arg) : base(arg)
{
}
public void createInstance()
{
DerivedClass p = new DerivedClass("test");
}
public static DerivedClass getInstance()
{
return new DerivedClass("test");
}
}
Regardless the major difference usage of abstract classes is to define abstract methods that subclasses must implement but you don't want to provide a default implementation for. For example suppose you have some kind of Thread class that has a Run method. You want to ensure that every call to Run first setups up some logging then does the real work of the thread and then stops logging. You could write an abstract Thread class like this:
public abstract Thread
{
protected Thread()
{
}
public void Run()
{
LogStart();
DoRun();
LogEnd();
}
protected abstract DoRun();
private void LogStart()
{
Console.Write("Starting Thread Run");
}
private void LogEnd()
{
Console.Write("Ending Thread Run");
}
}
public class HelloWorldThread : Thread
{
public HelloWorldThread()
{
}
protected override DoRun()
{
Console.Write("Hello World");
}
}
Another thing to consider, that I didn't see other people mention, is that your code may be maintained in the future. If the maintainer adds a public constructor to a class, then it can be instantiated. This might break your design, so you should prevent it (or design to accommodate it).
To prevent other people from making these kinds of changes, you can comment your code. Or, as other people said, use "abstract" to explicitly document your intent.
Well, the first difference that comes to mind is that an abstract class can not be instantiated, but a class with protected constructors could be instantiated throw another public method.
A common example of this might be something like the Singleton pattern: http://en.wikipedia.org/wiki/Singleton_pattern
if you inherit an abstract class from another abstract class, you do not have to satisfy abstract methods, but you do with a normal class with protected ctors. Examples
public abstract class Parent
{
protected abstract void AMethod();
}
public abstract class Child: Parent
{
// does not implement AMethod, and that's ok
}
public class Child2: Parent
{
// does not implement AMethod, and that will cause a compile error
}
If your intent is to only allow static uses of the class (i.e. not to use it as a pure base class) then you should use the static keyword instead; the CLR will prevent instances of the class being created via any method including Reflection (AFAIK).

C#: Determine derived object type from a base class static method

In a C# program, I have an abstract base class with a static "Create" method. The Create method is used to create an instance of the class and store it locally for later use. Since the base class is abstract, implementation objects will always derive from it.
I want to be able to derive an object from the base class, call the static Create method (implemented once in the base class) through the derived class, and create an instance of the derived object.
Are there any facilities within the C# language that will allow me to pull this off. My current fallback position is to pass an instance of the derived class as one of the arguments to the Create function, i.e.:
objDerived.Create(new objDerived(), "Arg1", "Arg2");
Try using generics:
public static BaseClass Create<T>() where T : BaseClass, new()
{
T newVar = new T();
// Do something with newVar
return T;
}
Sample use:
DerivedClass d = BaseClass.Create<DerivedClass>();
Summary
There are two main options. The nicer and newer one is to use generics, the other is to use reflection. I'm providing both in case you need to develop a solution that works prior to .NET 2.0.
Generics
abstract class BaseClass
{
public static BaseClass Create<T>() where T : BaseClass, new()
{
return new T();
}
}
Where the usage would be:
DerivedClass derivedInstance = BaseClass.Create<DerivedClass>();
Reflection
abstract class BaseClass
{
public static BaseClass Create(Type derivedType)
{
// Cast will throw at runtime if the created class
// doesn't derive from BaseClass.
return (BaseClass)Activator.CreateInstance(derivedType);
}
}
Where the usage would be (split over two lines for readability):
DerivedClass derivedClass
= (DerivedClass)BaseClass.Create(typeof(DerivedClass));
You want to create a new instance of derived from inside another instance of derived, using a static factory method on the abstract base class? if so, I wonder Why... But ...
public abstract class MyBase
{
public static T GetNewDerived<T>() where T : MyBase, new()
{
return new T();
}
}
public class DerivedA : MyBase
{
public static DerivedA GetNewDerived()
{
return GetNewDerived<DerivedA>();
}
}
public class DerivedB : MyBase
{
public static DerivedB GetNewDerived()
{
return GetNewDerived<DerivedB>();
}
}
Is this what you want ?
Sounds like you need to make the Create() method abstract. And once you do that you might as well rename it and make it the constructor as well. Then you can have a different Init() method that you call after the object is constructed if you need to, and normal polymorphism effects will handle things.
You can't do it without outside information; either the type of the derived class, an instance of it, or the fully-qualified name of the derived class. Any of these are equivalent to what you're already doing; there isn't a better solution I'm aware of. The very nature of static methods precludes anything more elegant.
I'm not sure what your design goals are but from what you asked it sounds like it might end up with alot of code smell. I think you should really look into the Inversion of Control(IoC) / Dependency Injection (DI) design patterns that are implemented in numerous frameworks such as Microsoft Unity, Castle Windsor, StructureMap, Ninject, Spring.Net and so forth.
I think if you look at using an IoC container it will solve your problem in a much cleaner and loosely coupled way.

Categories

Resources