Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Instantiating a class of type x at runtime

Instantiating a class of type x at runtime

Scheduled Pinned Locked Moved C#
questiontutorial
3 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    Anonymous
    wrote on last edited by
    #1

    Hi, I cannot find how to create a class at runtime... if I know the type of the object, and need to create an instance.. foo myObject = new foo(); Type t = myObject.GetType(); // how do I create a new object of type t ??

    S S 2 Replies Last reply
    0
    • A Anonymous

      Hi, I cannot find how to create a class at runtime... if I know the type of the object, and need to create an instance.. foo myObject = new foo(); Type t = myObject.GetType(); // how do I create a new object of type t ??

      S Offline
      S Offline
      Stefan Troschuetz
      wrote on last edited by
      #2

      Take a look at the Activator.CreateInstance method.


      www.troschuetz.de

      1 Reply Last reply
      0
      • A Anonymous

        Hi, I cannot find how to create a class at runtime... if I know the type of the object, and need to create an instance.. foo myObject = new foo(); Type t = myObject.GetType(); // how do I create a new object of type t ??

        S Offline
        S Offline
        shaunAustin
        wrote on last edited by
        #3

        The way i tend to do it is to get the constructor (usually the parameterless one) and call invoke on it using reflection.. Type t = .... ConstructorInfo constructor = t.GetConstructor(System.Type.EmptyTypes); object newObject = constructor.Invoke(null); ----------------------------------------------------------------------- Shaun Austin: .NET Specialist. Spreading the word of .NET to the world... well the UK... well my tiny corner of it!! :-D

        1 Reply Last reply
        0
        Reply
        • Reply as topic
        Log in to reply
        • Oldest to Newest
        • Newest to Oldest
        • Most Votes


        • Login

        • Don't have an account? Register

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • World
        • Users
        • Groups