Search code examples
c#dynamicrtti

C#: Create variable with typename in runtime (rtti?)


I need to create some variable with some predefined type which stored in other variable value. In pseudo code it looks like:

string typeName = "int";
object refToObj;
create data refToObj type typename.

write refToObj.getSize();

This pseudo-code must create var refToObj with type int, and then return 4 in output (write instruction.. ).

How can I do this in C#?


Solution

  • Something like the following?

    Type t = Type.GetType("System.Int32");
    
    Console.WriteLine("Sizeof: " + System.Runtime.InteropServices.Marshal.SizeOf(y));   
    Console.WriteLine("Type: " + t);
    
    var x = Activator.CreateInstance(t);
    
    Console.WriteLine("Value: " + x);
    

    Will output:

    Sizeof: 4
    Type: System.Int32
    Value: 0
    

    NOTE: int is an alias to the underlying System type which would differ on 32/64-bit operating systems. For Activator.CreateInstance you need to appropriate system types for it to succeed although you could have some form of Dictionary mapping.