Creating C# objects at run-time is easy. Just call the Activator.CreateInstance method.
For example, to create the same type of object as the current object using its default constructor:
Activator.CreateInstance( this.GetType() );
To better illustrate how this is done, below is a complete console program you can run. In this simple example, there is a Shape base class, and some derived shapes such as Circle and Square. The object construction code is used in the Shape’s “New” method, which could be used by a Shape factory class (not shown).
By default, the “New” method uses “this.GetType()” to construct the same type of Shape as the current object. This eliminates the need for each derived class to implement the “New” method. But if desired, shapes can override the “New” method to alter the construction process somehow. In this example, the SmallSquare class overrides the “New” method to ensure that no squares larger than 20×20 are created.
using System; using System.Drawing; namespace ConstructorThroughReflection { class Program { static void Main( string[] args ) { Circle c1 = new Circle( new Size( 2, 3 ) ); Circle c2 = c1.New( new Size( 10, 5 ) ) as Circle; Square s1 = new Square( new Size( 3, 4 ) ); SmallSquare ss1 = new SmallSquare( new Size( 7, 1 ) ); SmallSquare ss2 = new SmallSquare( new Size( 100, 100 ) ); Console.ReadLine(); } } abstract public class Shape { public Shape() {} public Shape( Size size ) { Console.WriteLine( "Shape={0}, Size={1}", this.GetType().Name, size ); this.Size = size; } public Size Size; virtual public Shape New( Size size ) { return Activator.CreateInstance( this.GetType(), size ) as Shape; } } public class Circle : Shape { public Circle() {} public Circle( Size size ) : base( size ) {} } public class Square : Shape { public Square() { } public Square( Size size ) : base( size ) { } } public class SmallSquare : Square { public SmallSquare() { } public SmallSquare( Size size ) : base( size ) { } override public Shape New( Size size ) { const int c_MaxSize = 20; int width = size.Width; int height = size.Height; if (width > c_MaxSize) width = c_MaxSize; if (height > c_MaxSize) height = c_MaxSize; size = new Size( width, height ); return new SmallSquare( size ); } } }
As you might expect, the console output from this program is:
Shape=Circle, Size={Width=2, Height=3}
Shape=Circle, Size={Width=10, Height=5}
Shape=Square, Size={Width=3, Height=4}
Shape=SmallSquare, Size={Width=7, Height=1}
Shape=SmallSquare, Size={Width=20, Height=20}