Is it possible to create an instance of a child object using the parent's constructor and passing it some kind of parameter (a string, in this case) to tell it the type of child that should be created?
-
1Is the child object's type inherited from the parent's type? If so, you are looking for a factory method. – Oliver Hanappi Dec 09 '10 at 15:17
-
+1 Oliver : sounds definitely like a factory to me too. – LaGrandMere Dec 09 '10 at 15:57
-
I'd recommend reading : http://www.dofactory.com/Patterns/PatternFactory.aspx – LaGrandMere Dec 09 '10 at 15:58
3 Answers
No. In C#, you create an instance of a class, then the runtime calls its constructor. By the time the constructor executes it's too late to pick another type.
However, a derived class' constructor always calls one of its base class' constructors, and you can use that to your advantage (to avoid repeating code).
People often create factories to do what you're talking about. For example, given the classes Parent
, Child1:Parent
, and Child2:Parent
, you might write a factory like this:
public class ParentFactory {
public Parent CreateParent(string type) {
switch(type) {
case "Child1":
return new Child1();
case "Child2":
return new Child2();
default:
throw new ArgumentException("Unexpected type");
}
}
}

- 47,787
- 8
- 93
- 120
If I understand you correctly, you want to create a class A and a class B that derives from A. Then you want to call new A("B")
and this should return you a new B object?
That is not possible.
However, I don't know what you are trying to accomplish, but maybe you should check out reflection, because it allows you to create an instance of a class by its name string.
http://msdn.microsoft.com/en-us/library/dex1ss7c.aspx
var obj = myAssembly.CreateInstance("myNamespace.myClassB");

- 9,519
- 12
- 52
- 74
Not sure if I understood right, but here is what I understood :)
public class parent:child
{
private child childObj;
public parent(string childName)
{
childObj = new child(childName);
}
}
public class child
{
private string name;
public child(string _name)
{
name = _name;
}
}

- 5,528
- 7
- 37
- 52
-
Not quite that. It does the same as the answer provided by GenericTypeTea, which is not what I wanted. – Farinha Dec 09 '10 at 15:43