-2

sorry if my English is not good. But there is a problem in C# I really need you guys to help me, thank you! If I have a class as below:

class InfoOfAnimal 
{
    public int Legs;
}

And I have an string array of 40 kind of animals named "Animals" including: cat, dog, ant... Each of "Animals", I want to create a new class InfoOfAnimal with the name is that elements of the array such as:

InfoOfAnimal dog= new InfoOfAnimal;

And when int Legs of dog has a value which is not null, the InfoOfAnimal cat will be automatically created and so on until the last element of the "Animals". I wonder is there any way to do that? Thank you you guys so much !

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
  • Variable names exist in your C# code as text. This text is static. The compiler translates these variable names to memory addresses or CPU registers. So, creating variable names dynamically is not possible because variables do not exist at runtime. – Olivier Jacot-Descombes Jan 29 '22 at 16:46

1 Answers1

1

Maybe it's because of your English but this idea is wrong about OOP usage.

Each of "Animals", I want to create a new class

Basically, you only have one class Animal and then you create an object for each animal.

Eg

class Animal
{
  public string Name{get;set;}

  public Animal(string name) 
  {
      Name = name;
  }
}

Then

var animals = new Animal[]
{
   new Animal("Dog"),
   new Animal("Cat"),
   new Animal("Pig"),
   new Animal("Chicken"),
}

If you want to have more information of Animal, eg, the number of legs, you can declare like

class Animal
{
  public string Name{get;set;}
  public int NumOfLegs{get;set;}
  public Animal(string name, int numOfLegs = 4) 
  {
      Name = name;
      NumOfLegs = numOfLegs;
  }
}

Then

var animals = new Animal[]
{
   new Animal("Dog"),
   new Animal("Cat"),
   new Animal("Pig"),
   new Animal("Chicken", 2),
   new Animal("Spider", 10),
}

Here you can see if I omit the value for the number of legs during creating an animal, the value is automatically set as 4. Otherwise, the expected value will be set. This is called Optional Parameter

Võ Quang Hòa
  • 2,688
  • 3
  • 27
  • 31