30

I have some problem. I want to creating instance of class by name. I found Activator.CreateInstance http://msdn.microsoft.com/en-us/library/d133hta4.aspx and it works fine, and I found this: Setting a property by reflection with a string value too.

But how to do both od this? I mean, I know the name of class, I know all properties in that class and I have this in string. For example:

string name = "MyClass";
string property = "PropertyInMyClass";

How to create instance and set some value to properties ?

Community
  • 1
  • 1
Adrian Księżarczyk
  • 810
  • 1
  • 11
  • 17
  • 1
    You almost canont do such thing. Object creation and setting the properties are completaly separate things from the Reflection point of view. Moreover, you will have to set each property separately. Of course you may create a helper function that will take your packed string, split it in parts, analyze and then create the object and set the proeprties. I think it should do the trick for you. – quetzalcoatl Aug 14 '12 at 18:54

3 Answers3

73

You could use Reflection:

using System;
using System.Reflection;

public class Foo
{
    public string Bar { get; set; }
}

public class Program
{
    static void Main()
    {
        string name = "Foo";
        string property = "Bar";
        string value = "Baz";

        // Get the type contained in the name string
        Type type = Type.GetType(name, true);

        // create an instance of that type
        object instance = Activator.CreateInstance(type);

        // Get a property on the type that is stored in the 
        // property string
        PropertyInfo prop = type.GetProperty(property);

        // Set the value of the given property on the given instance
        prop.SetValue(instance, value, null);

        // at this stage instance.Bar will equal to the value
        Console.WriteLine(((Foo)instance).Bar);
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 2
    @Darin, i tested the same code and it returns error as "Could not load type 'Foo' from assembly 'GenerateClassDynamically_ConsoleApp1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'." . The exception type is "System.TypeLoad Exception". I am not understanding why it is appearing ? – Chandan Kumar Jul 25 '14 at 09:23
  • @Darin, i tested the same code and it returns error as "Could not load type 'Foo' from assembly 'GenerateClassDynamically_ConsoleApp1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'." . The exception type is "System.TypeLoad Exception". I am not understanding why it is appearing ? Please Help me. I have the same requirement which gets a SAP service and i need to generate class and add properties to that class dynamically and send it back to the service to get the response data. – Chandan Kumar Jul 25 '14 at 09:28
  • Worked for me using https://github.com/NdubuisiJr/TypeExtender ty – Rihard Novozhilov Jun 09 '22 at 16:07
  • If you use a custom namespace, you need to add do to the name, so if your namespace is Dummy, the name should be "Dummy.Foo". – Gerard Jaryczewski Aug 25 '23 at 17:02
3

If you had System.TypeLoad Exception, your class name is wrong.

To method Type.GetType you must enter assembly-qualified name. That is with the project name For example: GenerateClassDynamically_ConsoleApp1.Foo

If it is in another assembly jou must enter assembly name after comma (details on https://stackoverflow.com/a/3512351/1540350): Type.GetType("GenerateClassDynamically_ConsoleApp1.Foo,GenerateClassDynamically_ConsoleApp1");

Community
  • 1
  • 1
-4
Type tp = Type.GetType(Namespace.class + "," + n.Attributes["ProductName"].Value + ",Version=" + n.Attributes["ProductVersion"].Value + ", Culture=neutral, PublicKeyToken=null");
if (tp != null)
{
    object o = Activator.CreateInstance(tp);
    Control x = (Control)o;
    panel1.Controls.Add(x);
}
cramopy
  • 3,459
  • 6
  • 28
  • 42
Hanan
  • 1