計算機科学のブログ

CAPTAIN AMAZING - THE DEATH OF THE OBJECT - structs, objects, value types, reference types

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 11(CAPTAIN AMAZING - THE DEATH OF THE OBJECT)、p.601(mini sharpen your pencil)の解答を求めてみる。

コード

Program.cs

using System.Runtime.CompilerServices;
using ConsoleApp1;

Canine spot = new("Spot", "pug");
Canine bob = spot;
bob.Name = "Spike";
bob.Breed = "beagle";
// My name is Spike and I'm a beagle.
spot.Speak();
Dog jake = new("Jake", "poodle");
Dog betty = jake;
betty.Name = "Betty";
betty.Breed = "pit bull";
// My name is Jake and I'm a poodle.
jake.Speak();

Dog.cs

namespace ConsoleApp1;

public struct Dog(string name, string breed)
{
    public string Name { get; set; } = name;
    public string Breed { get; set; } = breed;

    public void Speak()
    {
        Console.WriteLine($"My name is {Name} and I'm a {Breed}.");
    }
}

Canine.cs

namespace ConsoleApp1;

public class Canine(string name, string breed)
{
    public string Name { get; set; } = name;
    public string Breed { get; set; } = breed;

    public void Speak()
    {
        Console.WriteLine($"My name is {Name} and I'm a {Breed}.");
    }
}

入出力結果(Terminal, Zsh)

% dotnet run
My name is Spike and I'm a beagle.
My name is Jake and I'm a poodle.
%