Reputation: 10672
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
Upvotes: 0
Views: 1732
Reputation: 109862
I'm not sure what you're ultimate aim is, but I'd like to make you aware of the ExpandObject type, in case you don't know about it.
That lets you dynamically add properties and methods to an object at run-time, as this code illustrates:
using System;
using System.Dynamic;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
dynamic expando = new ExpandoObject();
expando.Name = "Name"; // Add property at run-time.
expando.PrintName = (Action) (() => Console.WriteLine(expando.Name)); // Add method at run-time.
test(expando);
}
private static void test(dynamic expando)
{
expando.PrintName();
}
}
}
Upvotes: 1
Reputation: 155726
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 A
and a class AFactory
in addition to class B : A
and a class BFactory
.
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:
public class A {
public A() {
// Default constructor
}
public A(A other) {
// Copy-constructor. Members of other will be copied into this instance.
}
}
public class B : A {
public B() {
}
public B(A other) : base(other) { // Notice how it calls the parent class's copy-constructor too
}
}
Then to "upgrade" an instance of A to an instance of B at runtime, just use the copy constructor:
A a = new A();
// some logic here
B upgradedA = new B( a );
Upvotes: 5