Search code examples
c#reflectionactivatoredmx-designer

instance with Activator not access the properties , reflection


I have a problem, I would like to make a generic method that instantiates the table of the model car, obviously by string.

I applied this code:

object item = Activator.CreateInstance(Type.GetType("eStartService." + tableName));

when I item.*something*, I do not see the properties of the table that should be called.

It is the first time that I use the reflection and maybe I'm doing something wrong?


Solution

  • That's because the compiler and intellisense treats the instantiated object as an "object" not the actual type. The object type does not have the properties you expect. You need to cast the instantiated object to the related type. Something like this:

    YourType item = (YourType)Activator.CreateInstance(Type.GetType("YourType"));
    item.property = ...;
    

    But since your type is determined at runtime not compile time, you have to use other approaches:

    Define a common interface between types

    If all of the types that are going to be instantiated have a common behavior, you may define a common interface, and implement it in those types. Then you can cast the instantiated type to that interface and use it's properties and methods.

    interface IItem { 
       int Property {
           get;
          set;
       }
    }
    class Item1 : IItem {
        public int Property {
            get;
           set;
        }
    }
    class Item2 : IItem {
        public int Property {
            get;
           set;
        }
    }
    IItem item = (IItem)Activator.CreateInstance(Type.GetType("eStartService." + tableName));
    item.Property1 = ...;
    

    Use reflection

    You can use reflection to access members of the instantiated type:

    Type type = Type.GetType("eStartService." + tableName);
    object item = Activator.CreateInstance(type);
    PropertyInfo pi = type.GetProperty("Property", BindingFlags.Instance);
    pi.SetValue(item, "Value here");
    

    There is no intellisense in this scenario of course.

    Use dynamic type

    dynamic item = Activator.CreateInstance(Type.GetType("eStartService." + tableName));
    item.Property = ...;
    

    The code above compiles but you still do not see intellisense suggestions because the "table" type determined at runtime.