計算機科学のブログ

data, types, objects, and references - Managing your app's data - Arrays can contain reference variables

Head First C Sharp: A Learner’s Guide to Real-World Programming with C Sharp and .NET (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)の Chapter 4(data, types, objects, and references - Managing your app’s data)、p.239(Sharpen your pencil)の解答を求めてみる。

コード

Program.cs

using ConsoleApp4;

Elephant[] elephants =
[
    new Elephant() { Name = "Lloyd", EarSize = 40 },
    new Elephant() { Name = "Lucinda", EarSize = 33 },
    new Elephant() { Name = "Larry", EarSize = 42 },
    new Elephant() { Name = "Lucille", EarSize = 32 },
    new Elephant() { Name = "Lars", EarSize = 44 },
    new Elephant() { Name = "Linda", EarSize = 37 },
    new Elephant() { Name = "Humphrey", EarSize = 45 },
];

Elephant biggestEars = elephants[0];
int[] ints = [0, 40, 42, 42, 44, 44, 45];
for (int i = 1; i < elephants.Length; i++)
{

    Console.WriteLine("Iteration #" + i);
    if (elephants[i].EarSize > biggestEars.EarSize)

    {
        biggestEars = elephants[i];
    }



    Console.WriteLine(biggestEars.EarSize == ints[i]);

}

Elephant.cs

namespace ConsoleApp4;

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..");
    }
}

入出力結果(Terminal, Zsh)

% dotnet run
Iteration #1
True
Iteration #2
True
Iteration #3
True
Iteration #4
True
Iteration #5
True
Iteration #6
True
%