本記事について
これから、C#に関する情報をまとめて記事にしていこうと思います。
多分10回くらいになるのかな。
基礎から発展形までまとめとこうと思います。
C# Lesson 01: 基礎と環境構築
目次
1. C#とは
C#(シーシャープ)は、Microsoftが開発したオブジェクト指向プログラミング言語です。
特徴
- 型安全性: コンパイル時に型エラーを検出
- ガベージコレクション: メモリ管理が自動化
- オブジェクト指向: クラス、継承、ポリモーフィズムをサポート
- モダンな構文: LINQ、async/await、パターンマッチングなど
- クロスプラットフォーム: Windows、Linux、macOSで動作
主な用途
- Webアプリケーション(ASP.NET Core)
- デスクトップアプリケーション(WPF、WinForms)
- モバイルアプリケーション(.NET MAUI)
- ゲーム開発(Unity)
- クラウドサービス(Azure Functions)
2. .NETプラットフォーム
.NETとは
.NETは、C#アプリケーションを実行するためのプラットフォームです。
┌─────────────────────────────────────────────┐
│ アプリケーション │
│ (Web API / デスクトップ / モバイル) │
├─────────────────────────────────────────────┤
│ .NET ランタイム │
│ (CLR: Common Language Runtime) │
├─────────────────────────────────────────────┤
│ 基本クラスライブラリ │
│ (BCL: Base Class Library) │
├─────────────────────────────────────────────┤
│ オペレーティングシステム │
│ (Windows / Linux / macOS) │
└─────────────────────────────────────────────┘
.NETのバージョン
- .NET Framework: Windows専用(レガシー)
- .NET Core: クロスプラットフォーム(3.1まで)
- .NET 5以降: 統合された.NET(推奨)
3. 開発環境の構築
必要なツール
1. .NET SDK
# インストール確認
dotnet --version
# 出力例: 8.0.100
公式サイト: https://dotnet.microsoft.com/download
2. エディタ/IDE
-
Visual Studio Code(軽量、無料)
- 拡張機能「C# Dev Kit」をインストール
- Visual Studio(フル機能、Community版は無料)
- JetBrains Rider(有料、クロスプラットフォーム)
プロジェクトの作成
# コンソールアプリケーション作成
dotnet new console -n MyFirstApp
# Web API作成
dotnet new webapi -n MyWebApi
# プロジェクト実行
cd MyFirstApp
dotnet run
プロジェクト構造
MyFirstApp/
├── MyFirstApp.csproj # プロジェクト設定ファイル
├── Program.cs # エントリーポイント
├── bin/ # ビルド出力
└── obj/ # 中間ファイル
.csprojファイルの例
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
4. 最初のプログラム
Hello World
// Program.cs
Console.WriteLine("Hello, World!");
.NET 6以降では、トップレベルステートメントにより簡潔に書けます。
従来の書き方(明示的なMain)
namespace MyFirstApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
コードの解説
-
namespace: 名前空間(コードの整理単位) -
class: クラス定義 -
static void Main: プログラムのエントリーポイント -
string[] args: コマンドライン引数 -
Console.WriteLine: コンソールに出力
5. 変数とデータ型
変数の宣言
// 型を明示
int age = 25;
string name = "田中太郎";
bool isActive = true;
// varキーワード(型推論)
var price = 1980; // int型と推論
var message = "Hello"; // string型と推論
値型(Value Types)
値型は、変数に直接値が格納されます。
| 型 | サイズ | 範囲 | 用途 |
|---|---|---|---|
byte |
1バイト | 0 〜 255 | 小さな正の整数 |
short |
2バイト | -32,768 〜 32,767 | 小さな整数 |
int |
4バイト | 約±21億 | 一般的な整数 |
long |
8バイト | 約±922京 | 大きな整数 |
float |
4バイト | ±3.4×10^38 | 単精度浮動小数点 |
double |
8バイト | ±1.7×10^308 | 倍精度浮動小数点 |
decimal |
16バイト | 高精度 | 金額計算 |
bool |
1バイト | true/false | 真偽値 |
char |
2バイト | Unicode文字 | 1文字 |
// 数値型の例
int deviceCount = 100;
long totalBytes = 1_000_000_000L; // アンダースコアで区切り可能
double percentage = 85.5;
decimal price = 19800.50m; // mサフィックス必須
// 真偽値
bool isEnabled = true;
bool isCompleted = false;
// 文字
char grade = 'A';
参照型(Reference Types)
参照型は、オブジェクトへの参照(アドレス)が格納されます。
// 文字列
string deviceName = "Windows PC";
string empty = "";
string? nullable = null; // null許容
// 配列
int[] numbers = { 1, 2, 3, 4, 5 };
string[] names = new string[3];
// オブジェクト
object obj = "任意の型を格納可能";
null許容型
// 値型のnull許容
int? nullableInt = null;
DateTime? nullableDate = null;
// null条件演算子
string? name = null;
int? length = name?.Length; // nameがnullならnull
// null合体演算子
string displayName = name ?? "名前なし";
定数
// const: コンパイル時定数
const int MaxRetryCount = 3;
const string ApiVersion = "v1.0";
// readonly: 実行時定数(コンストラクタで設定可能)
public readonly DateTime CreatedAt = DateTime.Now;
6. 演算子
算術演算子
int a = 10, b = 3;
int sum = a + b; // 13(加算)
int diff = a - b; // 7(減算)
int product = a * b; // 30(乗算)
int quotient = a / b; // 3(除算、整数)
int remainder = a % b; // 1(剰余)
// インクリメント/デクリメント
int count = 0;
count++; // 1
count--; // 0
++count; // 1(前置)
--count; // 0(前置)
比較演算子
int x = 5, y = 10;
bool isEqual = x == y; // false
bool isNotEqual = x != y; // true
bool isLess = x < y; // true
bool isGreater = x > y; // false
bool isLessOrEqual = x <= y; // true
bool isGreaterOrEqual = x >= y; // false
論理演算子
bool a = true, b = false;
bool and = a && b; // false(AND)
bool or = a || b; // true(OR)
bool not = !a; // false(NOT)
// 短絡評価
// &&は左がfalseなら右を評価しない
// ||は左がtrueなら右を評価しない
複合代入演算子
int value = 10;
value += 5; // value = value + 5 → 15
value -= 3; // value = value - 3 → 12
value *= 2; // value = value * 2 → 24
value /= 4; // value = value / 4 → 6
value %= 4; // value = value % 4 → 2
三項演算子
int score = 75;
string result = score >= 60 ? "合格" : "不合格";
// scoreが60以上なら"合格"、そうでなければ"不合格"
null関連演算子
string? input = null;
// null条件演算子(?.)
int? length = input?.Length; // null
// null合体演算子(??)
string output = input ?? "デフォルト値"; // "デフォルト値"
// null合体代入演算子(??=)
input ??= "値がなければこれ"; // inputがnullなら代入
7. 型変換
暗黙的変換(Implicit Conversion)
小さい型から大きい型へは自動変換されます。
int intValue = 100;
long longValue = intValue; // int → long(自動)
double doubleValue = intValue; // int → double(自動)
明示的変換(Explicit Conversion / キャスト)
大きい型から小さい型へは明示的なキャストが必要です。
double doubleValue = 123.456;
int intValue = (int)doubleValue; // 123(小数点以下切り捨て)
long longValue = 1000L;
int converted = (int)longValue; // 明示的キャスト
変換メソッド
// 文字列 → 数値
string numberStr = "123";
int number1 = int.Parse(numberStr); // 変換失敗で例外
bool success = int.TryParse(numberStr, out int number2); // 安全な変換
// 数値 → 文字列
int value = 456;
string str1 = value.ToString();
string str2 = $"{value}"; // 文字列補間
// Convertクラス
int fromString = Convert.ToInt32("789");
string fromInt = Convert.ToString(789);
bool fromInt2 = Convert.ToBoolean(1); // true
文字列補間
string name = "田中";
int age = 30;
decimal salary = 500000.50m;
// 文字列補間(推奨)
string message = $"名前: {name}, 年齢: {age}歳";
// 書式指定
string formatted = $"給与: {salary:C}"; // 通貨形式
string padded = $"ID: {age:D5}"; // 00030
string percent = $"割合: {0.856:P1}"; // 85.6%
8. 演習問題
問題1: 変数宣言
以下の要件を満たす変数を宣言してください。
- デバイス名(文字列)
- デバイス数(整数)
- 有効フラグ(真偽値)
- 価格(金額として正確に扱う)
解答例
string deviceName = "Surface Pro";
int deviceCount = 50;
bool isEnabled = true;
decimal price = 198000.00m;
Console.WriteLine($"デバイス: {deviceName}");
Console.WriteLine($"台数: {deviceCount}");
Console.WriteLine($"有効: {isEnabled}");
Console.WriteLine($"価格: {price:C}");
問題2: null安全な処理
ユーザー名がnullの場合は「ゲスト」と表示するコードを書いてください。
解答例
string? userName = null;
// 方法1: null合体演算子
string displayName = userName ?? "ゲスト";
// 方法2: 三項演算子
string displayName2 = userName != null ? userName : "ゲスト";
// 方法3: string.IsNullOrEmpty
string displayName3 = string.IsNullOrEmpty(userName) ? "ゲスト" : userName;
Console.WriteLine($"ようこそ、{displayName}さん");
問題3: 型変換
文字列 "12345" を整数に変換し、2倍にした値を表示してください。
変換に失敗した場合は「変換エラー」と表示してください。
解答例
string input = "12345";
if (int.TryParse(input, out int number))
{
int doubled = number * 2;
Console.WriteLine($"結果: {doubled}"); // 24690
}
else
{
Console.WriteLine("変換エラー");
}
問題4: 計算と表示
以下の計算を行い、結果を表示してください。
- 100台のデバイスを5部署に均等配分
- 1台あたりの価格が35,000円の場合の総額
解答例
int totalDevices = 100;
int departments = 5;
decimal pricePerDevice = 35000m;
int devicesPerDept = totalDevices / departments;
int remaining = totalDevices % departments;
decimal totalPrice = pricePerDevice * totalDevices;
Console.WriteLine($"部署あたり: {devicesPerDept}台");
Console.WriteLine($"余り: {remaining}台");
Console.WriteLine($"総額: {totalPrice:C}");
問題5: 条件判定
デバイスの状態コードに基づいて状態名を表示してください。
- 0: "無効"
- 1: "有効"
- 2: "保留中"
- それ以外: "不明"
解答例
int statusCode = 1;
string statusName = statusCode switch
{
0 => "無効",
1 => "有効",
2 => "保留中",
_ => "不明"
};
// または三項演算子のネスト(非推奨だが可能)
string statusName2 = statusCode == 0 ? "無効" :
statusCode == 1 ? "有効" :
statusCode == 2 ? "保留中" : "不明";
Console.WriteLine($"状態: {statusName}");
まとめ
このレッスンで学んだこと:
- C#と.NETプラットフォームの概要
- 開発環境のセットアップ
- 変数とデータ型(値型・参照型)
- 各種演算子の使い方
- 型変換とnull安全な処理
次のレッスンでは、制御構文(if、switch、ループ)とメソッドについて学びます。