-1

I am trying to make a function where I either pass a class name or an empty object and then build a new one and add it to a list. I have tried a few different ways that I've found online but it doesn't seem to work for passing as a function or making the object, not both and none for the list.

    class Program
    {
        static void Main(string[] args)
       {
           Read("TestObject");
       }
       static void Read(string classname)
       {
           List<Object> listObject = new List<object>(); //Not sure what to do
           typeOf(classname) n = new typeOf(classname)(); //Not sure what to do
           listObject.Add(n);
       }
    }

    public class TestObject
    {
        public string Col1 { get; set; }
        public string Col2 { get; set; }
    }
user2920788
  • 364
  • 4
  • 17
  • You can use [Assembly.GetType()](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.gettype?view=netframework-4.8) and [Activator.CreateInstance()](https://learn.microsoft.com/en-us/dotnet/api/system.activator.createinstance?view=netframework-4.8). – itsme86 Jun 10 '19 at 19:34

2 Answers2

1

Following this post, use:

public object GetInstance(string strFullyQualifiedName)
{         
     Type t = Type.GetType(strFullyQualifiedName); 
     return  Activator.CreateInstance(t);         
}
mzavarez
  • 61
  • 8
0

try this example in linqpad. you missing fully qualified class name (in this case it would be "UserQuery+test")

void Main()
{
    test tt = new test();
    GetInstance(tt.GetType().ToString());
}

public object GetInstance(string strFullyQualifiedName)
{
    var t = Type.GetType(strFullyQualifiedName).Dump();
    var res = Activator.CreateInstance(t);
    return  res;
}

public class test{
    public int id {get;set;}
    public test(){}
}

Power Mouse
  • 727
  • 6
  • 16