Reputation: 1
I have a class "Animals" which contains instance variable name and a set method accordingly
public void setName(string newName) { name = newName; }
I have other childclasses that inherits from "Animals"
I create an object from one of these and add it to my List< Animals > accordingly:
Turtle anAnimal = new Turtle();
//add to list
list.Add(anAnimal);
I assign properties in relation to every class like this:
//assigning all values
//bird info
foreach (var Animals in list.OfType<Birds>())
{
Animals.setFeatherColor(feather_color);
Animals.setWingspan(wingspan);
}
//reptile info
foreach (var Animals in list.OfType<Reptiles>())
{
Animals.setScalesColor(scales_color);
Animals.setVenemous(Venemous);
}
//animal info
foreach (var Animals in list.OfType<Animals>())
{
Animals.setId(list);
Animals.setAge(age);
Animals.setDiet(diet);
Animals.setGender(gender);
Animals.setName(name);
}
5.This is where the problem is: Animals.setName(name) assigns the same value every time I create a new animal with different names
6.name comes from textbox.Text;
Why is this happening? thank you (I am not forgetting to change textbox.Text)
Upvotes: 0
Views: 65
Reputation: 1035
Looks like there's a lot of code missing, yet my understanding is that you have a superclass called Animals
and a series of derived classes Bird
, Reptile
and such... so when you call Animals.SetName(name)
you're calling it within a foreach
loop that won't actually filter anything, since all of your classes are derived from the Animals
class.
public class Animal
{
public string name { get; set; }
}
public class Bird : Animal { }
public class Reptile : Animal { }
static void Main(string[] args)
{
List<Animal> animals= new List<Animal>();
Bird bird = new Bird();
bird.name = "bird";
Reptile reptile = new Reptile();
reptile.name = "reptile";
animals.Add(bird); animals.Add(reptile);
foreach (var animal in animals.OfType<Animal>())
{
Console.WriteLine(animal.name); // writes 'bird', 'reptile'
}
}
Upvotes: 1