計算機科学のブログ

types and references - Getting the reference - swap the references

Head First C#: A Learner’s Guide to Real-World Programming with C# and .NET Core (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)のChapter 4(types and references - Getting the reference)、p.194(Exercise)の解答を求めてみる。

コード

Elephant.cs

using System;
namespace MyFirstConsoleApp
{
    public class Elephant
    {
        public string Name;
        public int EarSize;

        public void WhoAmI()
        {
            Console.WriteLine($"My name is {Name}.");
            Console.WriteLine($"My ears are {EarSize} inches tall.");
        }
    }
}

コード

Program.cs

using System;

namespace MyFirstConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Elephant lucinda = new Elephant() { Name = "Lucinda", EarSize = 33 };
            Elephant lloyd = new Elephant() { Name = "Lloyd", EarSize = 40 };

            Console.WriteLine(
                $"Press 1 for {lloyd.Name}, " +
                $"2 for {lucinda.Name}, " +
                $"3 to swap");
            while (true)
            {
                char key = Console.ReadKey(true).KeyChar;
                Console.WriteLine($"You pressed {key}");
                if (key == '1')
                {
                    Console.WriteLine("Calling lloyd.WhoAmI()");
                    lloyd.WhoAmI();
                }
                else if (key == '2')
                {
                    Console.WriteLine("Calling lucinda.WhoAmI()");
                    lucinda.WhoAmI();
                }
                else if (key == '3')
                {
                    Console.WriteLine("References have been swapped");
                    Elephant t = lucinda;
                    lucinda = lloyd;
                    lloyd = t;
                }
                else
                {
                    Console.WriteLine("Invalid key");
                }
                Console.WriteLine();
            }
        }
    }
}

入出力結果(Terminal, Zsh, csi(C# Interactive))

Press 1 for Lloyd, 2 for Lucinda, 3 to swap
You pressed 1
Calling lloyd.WhoAmI()
My name is Lloyd.
My ears are 40 inches tall.

You pressed 2
Calling lucinda.WhoAmI()
My name is Lucinda.
My ears are 33 inches tall.

You pressed 3
References have been swapped

You pressed 1
Calling lloyd.WhoAmI()
My name is Lucinda.
My ears are 33 inches tall.

You pressed 2
Calling lucinda.WhoAmI()
My name is Lloyd.
My ears are 40 inches tall.

You pressed 3
References have been swapped

You pressed 1
Calling lloyd.WhoAmI()
My name is Lloyd.
My ears are 40 inches tall.

You pressed 2
Calling lucinda.WhoAmI()
My name is Lucinda.
My ears are 33 inches tall.