I'm trying to write a function which creates an object of Type t and assign its properties.
internal static object CreateInstanceWithParam(Type t, dynamic d)
{
//dynamic obj = t.GetConstructor(new Type[] { d }).Invoke(new object[] { d });
dynamic obj = t.GetConstructor(new Type[] { }).Invoke(new object[] { });
foreach (var prop in d.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
//prop.Name,
//prop.GetValue(d, null);
// assign the properties and corresponding values to newly created object ???
}
return obj;
}
Then I should be able to use this for any kind of class types like
IUser user = (IUser)CreateInstanceWithParam(userType, new { UserID = 0, Name = "user abc", LoginCode = "abc", DefaultPassword = "xxxxxx" });
IUnit newUnit = (IUnit)CreateInstanceWithParam(unitType, new { ID = 3, Code = "In", Name = "Inch", Points = "72" })
How can I assign the property prop.Name
to obj
?
dynamic
at all? If you're doing everything with reflection, I can't see that you're actually doing anything that makes use of it beingdynamic
. – Jon Skeet Jun 20 at 7:22Reflection
namespace. – Sen Jacob Jun 20 at 7:25