Thursday, July 29, 2010

How to create objects using string type name - C#

namespace ActiveTest
{
    public partial class Test1 : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Type type = Type.GetType("ActiveTest.Circle");
            IShape circle = Activator.CreateInstance(type) as IShape;
            ///
            /// you can cast your object to super level
            /// of if you have interface members you can 
            /// invoke them using interface members
            ///
            circle.Draw();
            circle.Paint();
 
            type = Type.GetType("ActiveTest.Squre");
            IShape squre = Activator.CreateInstance(type) as IShape;
            squre.Draw();
            squre.Paint();
        }
    }
    public interface  IShape
    {
        void Paint();
        void Draw();
    }
    public class Circle : IShape
    {
        #region IShape Members
 
        public void Paint()
        {
            ///
            /// Paint Circle 
            ///
        }
        public void Draw()
        {
            ///
            /// Draw Circle
            ///
        }
 
        #endregion
    }
    public class Squre : IShape
    {
        #region IShape Members
 
        public void Paint()
        {
            ///
            /// Paint squre
            ///
        }
        public void Draw()
        {
            ///
            /// Draw squre
            /// 
        }
 
        #endregion
    }
}

No comments:

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...