Toby Turner May
Toby Turner May

Reputation: 31

C# Foreach Loop Issue

I was just making this program to experiment with lists and such, and I was curious as to why in the foreach loop the Object always shows up as the "Minecraft" Wish object. Is it because it was the last Wish object to be created? And how can I fix it, so all 3 Wish objects which have been declared show up? Thanks!


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Wish iPod = new Wish("iPod", "Various", 299.00);
            Wish Phone = new Wish("New Phone", "Various", 00.00);
            Wish Minecraft = new Wish("Minecraft Account", "www.minecraft.net", 30.00);

            List<Wish> Wishlist = new List<Wish>();
            Wishlist.Add(Phone);
            Wishlist.Add(iPod);
            Wishlist.Add(Minecraft);
            Console.WriteLine("Toby's Wishlist");
            Console.WriteLine("If cost is 00.00, the Wish's cost varies.");
            Console.WriteLine("              ");
            foreach (Wish wish in Wishlist)
            {
                Console.WriteLine("---Wish---");
                Console.WriteLine("Name: {0}", wish.getName());
                Console.WriteLine("Store: {0}", wish.getStore());
                Console.WriteLine("Cost: ${0}", wish.getCost().ToString());
                Console.WriteLine("----------");
                Console.WriteLine("           ");
            }
            Console.ReadLine();

        }
    }
    public class Wish
    {
        static string Name, Store;
        static double ApproxCost;
        public Wish(string name, string store, double approxCost)
        {
            Name = name;
            Store = store;
            ApproxCost = approxCost;
        }

        public string getName()
        {
            return Name;
        }
        public string getStore()
        {
            return Store;
        }
        public double getCost()
        {
            return ApproxCost;
        }
    }
}

Upvotes: 3

Views: 152

Answers (2)

Reza Sadr
Reza Sadr

Reputation: 273

It's because in class Wish you declared Name, Score, and ApproxCost as static.

Upvotes: 1

zerkms
zerkms

Reputation: 255115

Remove static from Wish members declaration

static means that the data will be shared across all the instances. So static members are also so called class variables. While not static members - are object variables.

Upvotes: 8

Related Questions