C indexer simple instance code

  • 2020-05-09 19:11:50
  • OfStack


public class Fruit
{
        string peach = "a round juicy fruit that has a soft yellow or red skin and a large hard seed in the center, or the tree that this fruit grows on";
        string orange = "a round fruit that has a thick orange skin and is divided into parts inside";
        string banana = "a long curved tropical fruit with a yellow skin";
        string apple = "a hard round fruit that has red, light green, or yellow skin and is white inside ";
        public string this[string fruitName]
        {
            get
            {
                switch (fruitName)
                {
                    case "peach":
                        return peach;
                    case "orange":
                        return orange;
                    case "banana":
                        return banana;
                    case "apple":
                        return apple;
                    default:
                        throw new Exception("wrong fruit name");
                }
            }
            set
            {
                switch (fruitName)
                {
                    case "peach":
                        peach = value;
                        break;
                    case "orange":
                        orange = value;
                        break;
                    case "banana":
                        banana = value;
                        break;
                    case "apple":
                        apple = value;
                        break;
                    default:
                        throw new Exception("wrong fruit name");
                }
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Fruit f = new Fruit();
            // Associative array access get methods 
            Console.WriteLine(f["peach"]);
            // Associative array access set methods 
            f["peach"] = "I like to eat peach.";
            Console.WriteLine(f["peach"]);
            Console.ReadLine();
        }
    }


Related articles: