CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jan 2010
    Posts
    3

    [RESOLVED] C# Create generic class from variable objecttype

    I have the following working code
    Main.cs
    Code:
    Bootstrap<ROC> boot = new Bootstrap<ROC>(selectedTool as ROC);
    Bootstrap.cs
    Code:
    class Bootstrap<T> where T : class, IBootstrappable {
            DataTable data;
    
            public Bootstrap(T selectedTool) {
                data = selectedTool.CreateBootstrapDataTable();
            }
    Tools.cs
    Code:
        public interface IBootstrappable {
            DataTable CreateBootstrapDataTable();
        }
    selectedTool has type ROC in this case, which is a derived class from StatisticalTool. However, the application should work for other derived classes as well.

    So I need something like
    Code:
    Type type = selectedTool.GetType();
    Bootstrap<type> b = new Bootstrap<type>(selectedTool as type);
    But this doesn't work. Who has the solution?

  2. #2
    Join Date
    Jun 2008
    Posts
    2,477

    Re: C# Create generic class from variable objecttype

    Generics are compile time entities. If you need dynamic creation of a certain type defined at runtime use reflection.

  3. #3
    Join Date
    Mar 2004
    Location
    Prague, Czech Republic, EU
    Posts
    1,701

    Re: C# Create generic class from variable objecttype

    Yes. You need the Type.MakeGenericType() method.
    • Make it run.
    • Make it right.
    • Make it fast.

    Don't hesitate to rate my post.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured