🤖

Create and Run Simple C# Console Applications メモ

2024/03/11に公開

この記録は、以下の freeCodeCamp の学習コンテンツのメモになります。

Install and Configure Visual Studio Code

Exercise - Install the .NET SDK

  • VSCode をインストール。(既に普段使っているので、とくに問題なし)
  • .NET 8 Software Development Kit をインストール。
    • わたしの場合は macOS での作業なので、macOS 版の SDK のバイナリをインストール。
    • macOS でも学習コースは進めていけそうです。
% dotnet --version
8.0.201

% dotnet -h

.NET 8.0 へようこそ!
---------------------
SDK バージョン: 8.0.201

テレメトリ
---------
.NET ツールは、エクスペリエンスの向上のために利用状況データを収集します。データは Microsoft によって収集され、コミュニティと共有されます。テレメトリをオプトアウトするには、好みのシェルを使用して、DOTNET_CLI_TELEMETRY_OPTOUT 環境変数を '1' または 'true' に設定できます。

... 以下略 ...
  • VSCode の拡張機能で、C# Dev Kit を追加。

プロジェクトを作成してみる

コマンドで作成してみる。

% dotnet new console -o ./CsharpProjects/TestProject
テンプレート "コンソール アプリ" が正常に作成されました。

作成後の操作を処理しています...
/Users/akiko/work/CsharpProjects/TestProject/TestProject.csproj を復元しています:
  復元対象のプロジェクトを決定しています...
  /Users/akiko/work/CsharpProjects/TestProject/TestProject.csproj を復元しました (260 ms)。
正常に復元されました。

% tree CsharpProjects
CsharpProjects
└── TestProject
    ├── Program.cs
    ├── TestProject.csproj
    └── obj
        ├── TestProject.csproj.nuget.dgspec.json
        ├── TestProject.csproj.nuget.g.props
        ├── TestProject.csproj.nuget.g.targets
        ├── project.assets.json
        └── project.nuget.cache

2 directories, 7 files

VSCode で開いてみると、こんなソースコード。

// Program.cs
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

ビルドしてみます。

% dotnet build
MSBuild のバージョン 17.9.4+90725d08d (.NET)
  復元対象のプロジェクトを決定しています...
  復元対象のすべてのプロジェクトは最新です。
  TestProject -> /..../CsharpProjects/TestProject/bin/Debug/net8.0/TestProject.dll

ビルドに成功しました。
    0 個の警告
    0 エラー

経過時間 00:00:27.52

% dotnet run
Hello, World!
  • VSCode からの実行でも OK。

Call Methods From the .NET Class Library Using C

学習のねらい

  • Write code that calls methods in the .NET Class Library.
    • .NET Class Library でメソッドを呼び出すコードを書きます。
  • Use an instance of .NET Class Library classes to call methods that maintain state.
    • クラスライブラリのインスタンスを利用します。状態管理のためにメソッドを呼び出します。
  • Use Intellisense in Visual Studio Code to learn more about a method, including its overloaded versions, its return value type, and its input parameter data types.
    • VSCode でメソッドやバージョンのオーバーロード、戻り値のデータ型、データ型に基づいたパラメーターについて学習します。
  • Use learn.microsoft.com to research what a method does, its overloaded versions, its return value type, its input parameters and what each parameter represents, and more.
    • これらの調査のために learn.microsoft.com のコンテンツを利用します。

Get started with .NET Libraries

  • What is the .NET Class Library?
  • The .NET Class Library is a collection of thousands of classes containing tens of thousands of methods.
  • .NET Class Library は、数千ものたくさんのクラスのコレクションです。そこには一万以上ものメソッドが含まれます。
  • Console クラスでは、Write(), WriteLine(), Read(), ReadLine() といったメソッドを保持します。
  • You don't need every book in the library, and you won't be using every class and method in the .NET Class Library.
    • クラスライブラリを全部知っている必要はありません。また、必ずしも使う必要はありません。
  • You don't need to research classes and methods without a reason. When you have trouble figuring out a programming task, you can use your favorite search engine to find blog posts, articles, or forums where other developers have worked through similar issues.
    • 必要になるまではクラスを探さなくても大丈夫。必要が出てきたら、好きな検索エンジンやブログ記事、フォーラムといったものを通して、類似の事象に合ったクラスを探せば良い。

Stateful versus stateless methods

  • In other words, stateless methods are implemented so that they can work without referencing or changing any values already stored in memory. Stateless methods are also known as static methods.
    • ステートレスメソッドはメモリ上に値を保持しておくものではない。スタティックメソッドとも呼ばれます。
    • Console.WriteLine() はスタティックメソッドの例です。
  • Stateful (instance) methods keep track of their state in fields, which are variables defined on the class. Each new instance of the class gets its own copy of those fields in which to store state.
    • ステートフル(インスタンス)メソッドはフィールドとして値を保持します。
    • Random クラスの Next() メソッドは、一見ステートレスメソッド(スタティックメソッド)のように見えるけれど、インスタンスを生成して利用することが前提。seed の元になる値をインスタンスで保持するので、ステートフル(インスタンス)メソッドになります。

Overloaded methods

  • An overloaded method is defined with multiple method signatures. Overloaded methods provide different ways to call the method or provide different types of data.
    • オーバーロードメソッドは複数のシグネチャを持ちます。
    • 異なるタイプのデータを渡すことができます。
      *Console.WriteLine() の例。オーバーロードとして19個のバリエーションがあります。
  • https://learn.microsoft.com/ja-jp/dotnet/api/system.console.writeline?view=net-7.0#-------
int number = 7;
string text = "seven";

Console.WriteLine($"{number} / {number.GetType()}");
Console.WriteLine();
Console.WriteLine($"{text} / {text.GetType()}");

出力結果。

7 / System.Int32

seven / System.String

Review the solution to discover and implement a method call challenge activity

  • 2つの値を比べて大きい方を largerValue にセットして、出力しましょう。
  • System.Mathクラスを使ってみましょう。
  • メソッドはインテリセンスやオンラインドキュメントから探してみましょう。

// 対応したもの
int firstValue = 500;
int secondValue = 600;
int largerValue = Math.Max(firstValue, secondValue);

Console.WriteLine(largerValue);

Challenge project - Develop foreach and if-elseif-else structures to process array data in C

このモジュールの最終課題の実装分。

int examAssignments = 5;

string[] studentNames = new string[] { "Sophia", "Andrew", "Emma", "Logan" };

int[] sophiaScores = new int[] { 90, 86, 87, 98, 100, 94, 90 };
int[] andrewScores = new int[] { 92, 89, 81, 96, 90, 89 };
int[] emmaScores = new int[] { 90, 85, 87, 98, 68, 89, 89, 89 };
int[] loganScores = new int[] { 90, 95, 87, 88, 96, 96 };

int[] studentScores = new int[10];

string currentStudentLetterGrade = "";

// display the header row for scores/grades
Console.Clear();
// Console.WriteLine("Student\t\tGrade\tLetter Grade\n");
Console.WriteLine("Student\t\tExam Score\tOverall\tGrade\tExtra Credit\n");

/*
The outer foreach loop is used to:
- iterate through student names
- assign a student's grades to the studentScores array
- sum assignment scores (inner foreach loop)
- calculate numeric and letter grade
- write the score report information
*/
foreach (string name in studentNames)
{
    string currentStudent = name;

    if (currentStudent == "Sophia")
        studentScores = sophiaScores;

    else if (currentStudent == "Andrew")
        studentScores = andrewScores;

    else if (currentStudent == "Emma")
        studentScores = emmaScores;

    else if (currentStudent == "Logan")
        studentScores = loganScores;

    // 5教科+追加教科合計、5教科のみ合計、追加教科のみ合計
    decimal sumAssignmentScores = 0;
    decimal baseScores = 0;
    int extraAssignmentScores = 0;

    // 最終的な生徒の点数の平均値、5教科のみの生徒の点数の平均値
    decimal currentStudentGrade = 0;
    decimal baseStudentGrade = 0;

    // カウンタ用。総計で何教科分まで計算したかのカウンタ / 追加教科のみのカウンタ
    int gradedAssignments = 0;
    int extraAssignments = 0;

    /*
    the inner foreach loop sums assignment scores
    extra credit assignments are worth 10% of an exam score
    */
    foreach (int score in studentScores)
    {
        gradedAssignments += 1;

        if (gradedAssignments <= examAssignments)
        {
            sumAssignmentScores += score;
            baseScores += score;
        }
        else
        {
            // 総合計はキャストして少数第2位まで
            sumAssignmentScores += (decimal) (score / 10.0);
            extraAssignmentScores += score;
            extraAssignments += 1;
        }
    }

    currentStudentGrade = (decimal)(sumAssignmentScores) / (examAssignments);
    baseStudentGrade = (decimal)(baseScores) / examAssignments;
    decimal credit = currentStudentGrade - baseStudentGrade;

    if (currentStudentGrade >= 97)
        currentStudentLetterGrade = "A+";

    else if (currentStudentGrade >= 93)
        currentStudentLetterGrade = "A";

    else if (currentStudentGrade >= 90)
        currentStudentLetterGrade = "A-";

    else if (currentStudentGrade >= 87)
        currentStudentLetterGrade = "B+";

    else if (currentStudentGrade >= 83)
        currentStudentLetterGrade = "B";

    else if (currentStudentGrade >= 80)
        currentStudentLetterGrade = "B-";

    else if (currentStudentGrade >= 77)
        currentStudentLetterGrade = "C+";

    else if (currentStudentGrade >= 73)
        currentStudentLetterGrade = "C";

    else if (currentStudentGrade >= 70)
        currentStudentLetterGrade = "C-";

    else if (currentStudentGrade >= 67)
        currentStudentLetterGrade = "D+";

    else if (currentStudentGrade >= 63)
        currentStudentLetterGrade = "D";

    else if (currentStudentGrade >= 60)
        currentStudentLetterGrade = "D-";

    else
        currentStudentLetterGrade = "F";

    // Student         Grade
    // Sophia:         92.2    A-

    Console.WriteLine($"{currentStudent}\t\t{baseStudentGrade}\t\t{currentStudentGrade}\t{currentStudentLetterGrade}\t{extraAssignmentScores / extraAssignments} ({credit} pts)");
}

// required for running in VS Code (keeps the Output windows open to view results)
Con
sole.WriteLine("\n\rPress the Enter key to continue");
Console.ReadLine();

Discussion