May be I can’t explain exactly in words what I am trying to achieve, but I think this sample code can do:
class A
{
public string Name
{
get;
set;
}
public virtual void Say()
{
Console.WriteLine("I am A");
Console.Read();
}
public bool ExtendA;
public A GetObject()
{
if (ExtendA)
return new B();
return this;
}
}
internal class B : A
{
public override void Say()
{
Console.WriteLine(string.Format("I am {0}",Name));
Console.Read();
}
}
class Program
{
static void Main(string[] args)
{
var a = new A() {ExtendA = true,Name="MyName"};
A ab = a.GetObject();
}
}
As per the above code when the field Exitend A is set to true, and when again I try to get the object of same type from the same instance of object, I get the object but it loose the value of property ‘Name’.
Any suggestion how can I return back the class B with properties of A?
Thanks
I suggest you read a book or other resource on design patterns. For this you’d use a factory pattern.
You’d have your base class
Aand a classAFactoryin addition to classB : Aand a classBFactory.At runtime you’d choose what you want to instantiate: A or B by using the factories:
IFactory factory = iWantClassA ? new AFactory() : new BFactory();
A a = factory.CreateInstance();
Although I agree with @ArnaudF in that I don’t see what you’re trying to accomplish. Why not just create subclass B directly?
UPDATE:
Having re-read your problem it sounds like you really just need a copy-constructor on your class, like so:
Then to “upgrade” an instance of A to an instance of B at runtime, just use the copy constructor: