• Some users have recently had their accounts hijacked. It seems that the now defunct EVGA forums might have compromised your password there and seems many are using the same PW here. We would suggest you UPDATE YOUR PASSWORD and TURN ON 2FA for your account here to further secure it. None of the compromised accounts had 2FA turned on.
    Once you have enabled 2FA, your account will be updated soon to show a badge, letting other members know that you use 2FA to protect your account. This should be beneficial for everyone that uses FSFT.

Coding questions about creating class instances?

JC0724

Weaksauce
Joined
Oct 11, 2008
Messages
105
Is it possible to instantiate a class inside of a for loop and continue to make a new instance of the class as I iterate threw the for loop?

Also can you have multiply instances with the same name but if I pass in different values in the Constructor, will all of the instances exist with the same name but with different values or will it keep over writing it self?

Can I create a string and then create an instance of animal with the variable/name of the string?

Is this possible below.

class animal {
};

string bob;

bob animal();
 
1. Yes.
2. If you use the same variable, no.
3. Depends on the language. I believe that PHP, for example, can.
 
What you actually call the instance of your class is arbitrary. If you want to name it, you could just set a property of the class. Pseudocode using C#:

Code:
class animal{
 public string name {get; set;}
}

animal someAnimal = new animal();

string someName = "Midget";

someAnimal.name = someName;
 
You'll need to keep a reference to the previous ones you created unless you want the garbage collector to clean them up. Example typed in browser, I think it works ;)
Code:
class Animal
{
  public Animal(string name)
  {
    Name = name;
  }

  public string Name { get; private set; }
}

class Program
{
  public static void main(string[] args)
  {
    const int animalCount = 10;

    var animals = new List<Animal>();
    for (int i = 0; i < animalCount; i++)
    {
      animals.Add(new Animal(Guid.NewGuid().ToString());
    }

    Console.WriteLine(String.Join(", ", animals));
  }
}
 
Back
Top