計算機科学のブログ

objects…get oriented! Making code make sense - Class, methods, instances, array, for loop 1

Head First C#: A Learner’s Guide to Real-World Programming with C# and .NET Core (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)のChapter 3(objects…get oriented! Making code make sense)、p.135(Sharpen your pencil)の解答を求めてみる。

コード

using System;

namespace MyFirstConsoleApp
{
    class Clown
    {
        public string Name;
        public int Height;
        public string TalkAboutYourself()
        {
            return "My name is " + Name +
                " and I'm " + Height + " inches tall.";
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Clown oneClown = new Clown();
            oneClown.Name = "Boffo";
            oneClown.Height = 14;
            Console.WriteLine(oneClown.TalkAboutYourself() ==
                "My name is Boffo and I'm 14 inches tall.");

            Clown anotherClown = new Clown();
            anotherClown.Name = "Biff";
            anotherClown.Height = 16;
            Console.WriteLine(anotherClown.TalkAboutYourself() ==
                "My name is Biff and I'm 16 inches tall.");

            Clown clown3 = new Clown();
            clown3.Name = anotherClown.Name;
            clown3.Height = anotherClown.Height - 3;
            Console.WriteLine(clown3.TalkAboutYourself() ==
                "My name is Biff and I'm 13 inches tall.");

            anotherClown.Height *= 2;
            Console.WriteLine(anotherClown.TalkAboutYourself() ==
                "My name is Biff and I'm 32 inches tall.");
        }
    }
}

入出力結果(Terminal)

True
True
True
True