I know this does not work, however does anyone have a way of making it work?
object obj = new object();
MyType typObj = new MyType();
obj = typObj;
Type objType = typObj.GetType();
List<objType> list = new List<objType>();
list.add((objType) obj);
EDIT:
Here is the current code: http://github.com/vimae/Nisme/blob/4aa18943214a7fd4ec6585384d167b10f0f81029/Lala.API/XmlParser.cs
The method I'm attempting to streamline is SingleNodeCollection
As you can see, it currently uses so hacked together reflection methods.
In Dynamic Typing, type checking is performed at runtime. For example, Python is a dynamically typed language. It means that the type of a variable is allowed to change over its lifetime. Other dynamically typed languages are -Perl, Ruby, PHP, Javascript etc.
Just as the assumption that all Strongly-typed languages are Statically-typed, not all Weakly-typed languages are Dynamically-typed; PHP is a dynamically-typed language, but C — also a weakly-typed language — is indeed statically-typed.
Dynamically-typed languages are those (like JavaScript) where the interpreter assigns variables a type at runtime based on the variable's value at the time.
Dynamic typing means that the type of the variable is determined only during runtime. Due to strong typing, types need to be compatible with respect to the operand when performing operations. For example Python allows one to add an integer and a floating point number, but adding an integer to a string produces error.
It seems you're missing an obvious solution:
object obj = new object();
MyType typObj = new MyType();
obj = typObj;
List<MyType> list = new List<MyType>();
list.Add((MyType) obj);
If you really need the dynamic route, then you could do something like this:
object obj = new object();
MyType typObj = new MyType();
obj = typObj;
Type objType = typObj.GetType();
Type listType = typeof(List<>);
Type creatableList = listType.MakeGenericType(objType);
object list = Activator.CreateInstance(creatableList);
MethodInfo mi = creatableList.GetMethod("Add");
mi.Invoke(list, new object[] {obj});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With