Q:

Null reference when trying to cast listbox.selecteditem?

So for a school assignment I have to make an animal shelter, 
There are two objects : Cats and Dogs, every new instance of an object is added to an object list  like this:  
    public Cat Cat { get; private set; }
    public Dog Dog { get; private set; }
    public List<Dog> Dogs = new List<Dog>();
    public List<Cat> Cats = new List<Cat>();

    public void NewCat(string name, Gender gender, string badHabits)
    {
        this.Cat = new Cat(name, gender, badHabits);
        Cats.Add(this.Cat);

    }

    public void NewDog(string name, Gender gender)
    {
        this.Dog = new Dog(name, gender);
        Dogs.Add(this.Dog);
    }  

with an update method both lists are added to a listbox like this:  
  private void Update()
    {
            lbAnimals.Items.Clear();
            lbAnimals.Items.Clear();
            foreach (Cat c in reservations.Cats)
        {
            lbAnimals.Items.Add(c.ToString());
        }
        foreach (Dog d in reservations.Dogs)
        {
            lbAnimals.Items.Add(d.ToString());
        }
    } 

And finally I need to cast the selected object in a listbox to a Dog object or a cat object, this is how it is done for a dog: 
 private void btnReserveDog_Click(object sender, EventArgs e)
    {
        if (this.reservations.Dog != null)
        { 
            var d=  lbAnimals.SelectedItem as Dog; 
                d.Reserve(txtReservor.Text); 
                this.btnReserveDog.Enabled = false;
            Update();
        }
    } 

No matter what I seem to try, when I cast the object it returns a null reference and I have no idea why, Any help would be much appreciated! 

A:

The items collection of a ListBox will accept objects of any type. You are currently converting your objects from Cat and Dog to string before adding, so of course when you use as and try to cast the string back to Dog, it fails. A Dog is not a string, which means you get null as the result (that's what as does when the cast fails).
All you should need to do is remove the .ToString(). I.e.:
private void Update()
{
    lbAnimals.Items.Clear();
    lbAnimals.Items.Clear();
    foreach (Cat c in reservations.Cats)
    {
        lbAnimals.Items.Add(c);
    }
    foreach (Dog d in reservations.Dogs)
    {
        lbAnimals.Items.Add(d);
    }
}

Then, when you are dealing with a Dog element in the collection, you'll get the Dog instance back when using as.
Of course, for Cat elements, the result will be null. It is still up to you to make sure you handle the null value (either by not trying to cast to Dog when it's a Cat and vice a versa, or by checking for the null result).

