3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C#基礎文法完全ガイド【図解×コード】初心者からゲーム開発まで

3
Posted at

🟣 C#基礎文法完全ガイド【図解×コード】

📌 はじめに

この記事では、C#の基本文法を図解とコードで分かりやすく解説します。C#/.NETでの開発やゲーム開発を始めたい方におすすめの内容です。

🖥️ C#ってどんな言語?

C#は以下のような場面でよく使われます:

  • Windowsアプリケーション
  • Webアプリケーション(ASP.NET Core)
  • ゲーム開発(Unity)
  • クラウドサービス(Azure)

🌍 C#の特徴(図解)


🧰 1. 開発環境の準備(.NET 10)

🔧 .NET SDKをインストールする

現在は .NET 10 が最新のLTS(長期サポート)版で推奨です(2028年11月までサポート)。

.NET と C# のバージョン対応

基本的には、使用できるC#のバージョンはインストールした .NET SDK(に含まれるコンパイラ)に準じます(必要に応じてプロジェクト設定で言語バージョンを指定できます)。

.NET バージョン C# バージョン サポート期限
.NET 10 C# 14 2028年11月(LTS)
.NET 9 C# 13 2026年5月
.NET 8 C# 12 2026年11月(LTS)
  • バージョン確認
    dotnet --version
    

エディタ

  • Visual Studio 2026(Windows向け統合開発環境・推奨)
  • Visual Studio Code + C# Dev Kit(軽量・クロスプラットフォーム)
  • Rider(有料だが高機能)

プロジェクトの作成

dotnet new console -n MyApp
cd MyApp
dotnet run

📘 2. 変数と型

よく使う型一覧

説明
int 整数 10, -5
double 小数 3.14
string 文字列 "Hello"
bool 真偽値 true / false

サンプルコード

int age = 30;
string name = "Taro";
bool isAdmin = true;

// 文字列補間($をつけると変数を埋め込めます)
Console.WriteLine($"Name: {name}, Age: {age}");

型推論(var)

右辺から型が明らかな場合、var を使って省略可能です。

var age = 30;           // int型と推論される
var name = "Taro";      // string型と推論される

🔀 3. 条件分岐(if / switch)

if 文

int age = 20;

if (age >= 20)
{
    Console.WriteLine("大人");
}
else
{
    Console.WriteLine("子供");
}

switch 文(従来型)

int n = 2;

switch (n)
{
    case 1:
        Console.WriteLine("One");
        break;
    case 2:
        Console.WriteLine("Two");
        break;
    default:
        Console.WriteLine("Other");
        break;
}

switch 文(パターンマッチング・C# 9以降)

C# 9以降では、リレーショナルパターンを使って範囲での分岐ができます。

int age = 20;

switch (age)
{
    case >= 20:
        Console.WriteLine("大人");
        break;
    default:
        Console.WriteLine("子供");
        break;
}

🔁 4. 繰り返し(for / while / foreach)

for 文

for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i);
}

while 文

int i = 0;
while (i < 5)
{
    Console.WriteLine(i);
    i++;
}

foreach 文

配列やコレクションの要素を順番に取り出します。

string[] fruits = { "Apple", "Banana", "Orange" };
foreach (var fruit in fruits)
{
    Console.WriteLine(fruit);
}

📦 5. 配列とコレクション

配列(Array)

サイズ固定です。

int[] nums = { 10, 20, 30 };

for (int i = 0; i < nums.Length; i++)
{
    Console.WriteLine(nums[i]);
}

List(動的配列)

サイズが可変で便利です。

using System.Collections.Generic;

List<int> nums = new List<int> { 10, 20, 30 };

// 追加
nums.Add(40);

// 削除
nums.Remove(20);

// 表示
foreach (int n in nums)
{
    Console.WriteLine(n);
}

🧩 6. メソッド

class Program
{
    static void Main(string[] args)
    {
        int result = Add(3, 5);
        Console.WriteLine($"Result: {result}");
    }

    static int Add(int a, int b)
    {
        return a + b;
    }
}

デフォルト引数

static void Greet(string name = "Guest")
{
    Console.WriteLine($"Hello, {name}!");
}

// 呼び出し
Greet();        // Hello, Guest!
Greet("Taro");  // Hello, Taro!

🧱 7. クラスとオブジェクト

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public void SayHello()
    {
        Console.WriteLine($"こんにちは、{Name}です");
    }
}

// 使用例
var p = new Person() { Name = "Taro", Age = 20 };
p.SayHello();

🎯 8. プロパティとフィールド

自動実装プロパティ

最もシンプルな形式です。

public int Age { get; set; }

field キーワード(C# 14 / .NET 10)

従来、{ get; set; } のような自動実装プロパティに入力チェックや整形などのロジックを入れたくなると、バッキングフィールド(例:private string _name;)を手動で用意する必要がありました。

C# 14 の field(コンテキストキーワード)を使うと、アクセサー内からコンパイラ生成のバッキングフィールドにアクセスできるため、手動のフィールド定義を省けます。

// 従来:バッキングフィールドを手動で定義
private string _name = string.Empty;
public string Name
{
    get => _name;
    set => _name = value?.Trim() ?? string.Empty;
}

// C# 14:fieldキーワードでコンパイラ生成のバッキングフィールドを参照できる
public string Name
{
    get; // ← getter は自動のまま
    set => field = value?.Trim() ?? string.Empty;
}

注意field は get / set / init のアクセサー本体の中だけで特別扱いされます。クラス内に field という名前の変数がある場合は、@field のようにエスケープして衝突を回避できます。


⏳ 9. 非同期処理(async/await)入門

async/awaitを使うと、時間のかかる処理を効率的に扱えます。

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        string content = await FetchDataAsync("https://example.com");
        Console.WriteLine($"取得したデータの長さ: {content.Length}");
    }

    static async Task<string> FetchDataAsync(string url)
    {
        using HttpClient client = new HttpClient();
        return await client.GetStringAsync(url);
    }
}

ポイント

  • async:このメソッドは非同期処理を含むことを示す
  • await:非同期処理の完了を待つ(スレッドをブロックしない)
  • Task / Task<T>:非同期処理の戻り値の型

⚠️ 10. 例外処理

try
{
    int a = 10;
    int b = 0;
    int result = a / b;
}
catch (DivideByZeroException e)
{
    Console.WriteLine($"エラー:{e.Message}");
}
finally
{
    Console.WriteLine("処理完了"); // エラーの有無に関わらず実行
}

🎉 まとめ

本記事では、C#の基本文法を図解とコードで解説しました。

  • 開発環境:.NET 10 SDKの準備
  • 基本構文:変数、条件分岐、ループ
  • データ構造:配列、List
  • オブジェクト指向:クラス、プロパティ
  • 非同期処理:async/await
  • 例外処理:try-catch-finally
  • C# 14の新機能:field キーワード

次のステップ

  1. LINQでデータ操作を簡潔にする方法を学ぶ
  2. ASP.NET CoreでWeb開発に挑戦する
  3. Unityでゲームを作ってみる
  4. Entity Framework Coreでデータベース操作を学ぶ

これからC#を学ぶ方の参考になれば嬉しいです!
参考になったら「いいね」👍 お願いします!

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?