Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic typing in C#

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.

like image 709
WedTM Avatar asked Jun 04 '09 16:06

WedTM


People also ask

What is dynamic typing in C?

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.

Does C have dynamic typing?

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.

What is dynamic typing in programming?

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.

What is dynamic typing explain with example?

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.


1 Answers

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});
like image 84
Jeff Moser Avatar answered Oct 13 '22 02:10

Jeff Moser