Create instance of type from 2 strings (type, value)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • codingvista
    New Member
    • Aug 2008
    • 1

    #1

    Create instance of type from 2 strings (type, value)

    Hey

    I have the type name as a string and the value also as a string. I want to create a generic method that can return an instance of the type, populated with the value. Is there a method somewhere that can do this or am I going to need to start from scratch?
  • Curtis Rutland
    Recognized Expert Specialist
    • Apr 2008
    • 3264

    #2
    I would think you will have to do this manually. There isn't a way to evaluate strings as statements, as far as I know.

    Comment

    • Plater
      Recognized Expert Expert
      • Apr 2007
      • 7872

      #3
      I think you can use System.Reflecti on to create an isntance of a class based on the string.
      Don't know much more about it though.

      Comment

      • TRScheel
        Recognized Expert Contributor
        • Apr 2007
        • 638

        #4
        Originally posted by Plater
        I think you can use System.Reflecti on to create an isntance of a class based on the string.
        Don't know much more about it though.
        While System.Reflecti on will work, its a fairly large tool to use if he is only dealing with a few classes.

        To the OP, if you have less than half a dozen classes that might be involved, I would create a method that checked the type and then passed the value to a prewritten parse method in each class (which is really easy to write if you override ToString) and returned the class.

        If you have something a bit more extensive I would research System.Reflecti on and Activator.Creat eInstance/Activator.Creat eInstanceFrom

        Comment

        Working...