Question

I'm loading an assembly generated on runtime that contains a class which has several attributes that need to be set.

From my research, I've found that this is possible using Reflection so here's how I load the assembly:

        Assembly a = Assembly.LoadFrom("ClassLibrary1.dll");
        Type t = (Type)a.GetTypes()[0];

Now I'm trying to define properties this way:

        object ClassObj = Activator.CreateInstance(t);
        PropertyInfo p= t.GetProperties()[0];
        int x=1;
        p.SetValue(ClassObj,x);

This doesn't seem to viable for me so I thought of using the "dynamic" type.

        dynamic ClassObj = Activator.CreateInstance(t);
        ClassObj.soma = 1; 

Unfortunately this doesn't seem to work.

It states that :

'object' does not contain a definition for 'soma'

Is there anyway I can Map the class into the dynamic var?

Edit :

Fields of dynamic ClassObj show up "soma" propriety

Was it helpful?

Solution

Its works fine to me, try this:

    public class TypeTest
    {
        public string mimimi { get; set; }
    }

   Type t = typeof(TypeTest);
   dynamic instanceTypeTeste = Activator.CreateInstance(t);
   instanceTipoTeste.mimimi = "test";

Possible problems in your code:

  • To change the value, property and class needs be Public
  • The correct sintax, because the property name is Case Sensitive
  • When you load a type, look if is the correct Type of your class

OTHER TIPS

When you use dynamic, you have to be sure all the properties you're trying to access are written correctly. Or your property isn't soma, it might be Soma instead, or Type t = (Type)a.GetTypes()[0]; isn't returning the type you expect.

I tried here with the same code, and when I tried to access a property with a different name, it threw the same exception.

You could also try to write all the path of your assembly:

Assembly a = Assembly.LoadFrom(@"C:\PathHere\ClassLibrary1.dll");

By the way, your class and properties must be public, otherwise you won't access it properly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top