1

I have an array filled with the names if some classes in my program .

string[] arr= new string[] {"company", "pokemon", "parents"}

is it possible to create an instance of a class like this:

list.Add(new class( arr[0] { "sdfs", "sfds", 123} ))
Daniel Mann
  • 57,011
  • 13
  • 100
  • 120
  • 1
    What are `sdfs`, `sfds` and `123`? – canton7 Feb 24 '19 at 17:03
  • 2
    Are you asking how to [instantiate a class given its name as a string](https://stackoverflow.com/q/223952/11683)? – GSerg Feb 24 '19 at 17:04
  • these are examples of my fileds in the classes for example: class Pokemon with name="sdfs"; type="sfds"; age=123; – Petkov Alexander Feb 24 '19 at 17:06
  • 1
    The approach does not make sense to me, as the different classes like Company, Pokemon and Parents would probably require different values for their fields/properties/constructor arguments. If so, there is little benefit in stuffing those class names into an array, as you will need to know precisely which class type is arr[0], arr[1], arr[2] to be able to choose the correct kind of arguments when trying to create an object. And since you have to know what class type arr[0] is, you can just forego using the class names array and use the class name directly like `list.Add(new Company() {...})` –  Feb 24 '19 at 18:25

1 Answers1

1

Maybe you are looking for object initialisers?

Assuming you have a class Pokemon:

class Pokemon {
    public string Name { get; set; }
    public string Type { get; set; }
    public int Age { get; set; }
}

and a List<Pokemon> called list, you can do this:

list.Add(new Pokemon { Name = "sdfs", Type = "sfds", Age = 123 });
Sweeper
  • 213,210
  • 22
  • 193
  • 313