オールインワン C# 入門サイト

このサイトについて

ここでは、C# を初めて学ぶ方や、基礎を復習したい方向けに、 C#と.NETの概要から開発環境構築、文法、オブジェクト指向、さらにデバッグやテスト、 一歩進んだ応用トピック(Generics, LINQ, 非同期など)まで幅広くカバーしています。

ページ上部のナビゲーションから各セクションへ移動できます。 一通り学習した後は、クイズに挑戦したり、サンプルプログラムを動かしてみましょう。

環境構築 & .NET

.NETエコシステムの概要

C# は .NET 上で動作する言語です。 近年はクロスプラットフォーム対応の「.NET (Core)」が主流であり、 Windows だけでなく Mac や Linux でも利用可能です。

Windows での開発

Visual Studio (Community 版) または VS Code が一般的です。 dotnet CLI を使ってプロジェクト作成・ビルド・実行が可能です。


// 例: コンソールアプリプロジェクトの作成
dotnet new console -o MyApp
cd MyApp
dotnet run

Mac / Linux での開発

公式サイトから .NET SDK をインストールすることで、同様に C# を利用できます。 VS Code + C#拡張機能があればブレークポイントによるデバッグも可能です。

C#の基本

C#とは?

C# (シーシャープ) は、マイクロソフトが開発したオブジェクト指向言語です。 Javaに似た構文を持ち、GenericsやLINQ、非同期などモダンな機能を数多く備えています。

Hello World


using System;

namespace HelloWorldApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

このように、Main メソッドがエントリポイントとして呼び出されます。

基本文法

変数とデータ型


int number = 10;
double pi = 3.14;
bool isActive = true;
string message = "Hello C#";

C# は強い型付け言語であり、var キーワードで型推論も可能です。

演算子

算術演算子、比較演算子、論理演算子などを使用できます。


int x = 5;
int y = 3;
Console.WriteLine(x + y); // 8
Console.WriteLine(x > y); // true

条件分岐・ループ

if / else / else if


int score = 85;
if(score >= 80) {
    Console.WriteLine("Excellent!");
} else if(score >= 60) {
    Console.WriteLine("Good!");
} else {
    Console.WriteLine("Keep trying!");
}

switch


int dayOfWeek = 2;
switch(dayOfWeek)
{
    case 0:
        Console.WriteLine("日曜日");
        break;
    case 1:
        Console.WriteLine("月曜日");
        break;
    case 2:
        Console.WriteLine("火曜日");
        break;
    default:
        Console.WriteLine("不明な曜日");
        break;
}

for / while / do-while


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

// whileループ
int j = 0;
while(j < 5) {
    Console.WriteLine(j);
    j++;
}

// do-whileループ
int k = 0;
do {
    Console.WriteLine(k);
    k++;
} while(k < 5);

オブジェクト指向

クラスとオブジェクト


class Person
{
    public string Name;
    public int Age;

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

class Program
{
    static void Main()
    {
        Person p = new Person();
        p.Name = "Taro";
        p.Age = 20;
        p.Greet();
    }
}

継承とポリモーフィズム


class Animal
{
    public string Name { get; set; }
    public virtual void Speak()
    {
        Console.WriteLine("何かを話す");
    }
}

class Dog : Animal
{
    public override void Speak()
    {
        Console.WriteLine("ワンワン");
    }
}

インターフェイス


interface IFlyable
{
    void Fly();
}

class Bird : IFlyable
{
    public void Fly()
    {
        Console.WriteLine("羽ばたいて飛ぶ");
    }
}

応用トピック

Generics (ジェネリクス)


List numbers = new List();
numbers.Add(10);
numbers.Add(20);

class Box
{
    public T Value { get; set; }
    public Box(T value)
    {
        Value = value;
    }
}

デリゲート・イベント


public delegate void MyDelegate(string msg);

public class Publisher
{
    public event MyDelegate OnPublish;

    public void Publish(string msg)
    {
        OnPublish?.Invoke(msg);
    }
}

LINQ


int[] data = {1,2,3,4,5,6};
var evens = from x in data
            where x % 2 == 0
            select x;

非同期 (async/await)


static async Task Main()
{
    Console.WriteLine("開始");
    await Task.Delay(1000);
    Console.WriteLine("終了");
}

デバッグ & テスト

Visual Studioでのデバッグ

  1. 行番号の左をクリックしてブレークポイントを設定
  2. 「デバッグ実行」ボタンで開始
  3. 停止したらローカル変数やステップ実行を確認

例外処理


try
{
    int num = int.Parse("abc");
}
catch(FormatException fe)
{
    Console.WriteLine("フォーマットエラー: " + fe.Message);
}
finally
{
    Console.WriteLine("終了処理");
}

ユニットテスト


using Xunit;

public class CalcTests
{
    [Fact]
    public void AddTest()
    {
        int result = Calc.Add(2, 3);
        Assert.Equal(5, result);
    }
}

public static class Calc
{
    public static int Add(int x, int y) => x + y;
}

xUnit、NUnit、MSTest などが有名です。dotnet test でテスト実行できます。

C#クイズ

ラジオボタンで答えを選んで「採点する」ボタンを押してください。

Q1. C# コンソールアプリのエントリポイントは?




Q2. 次のうち整数型ではないのは?




Q3. C# の例外処理に使われるキーワードの組み合わせは?




サンプルプログラム

1. ユーザー入力を受け取る


using System;

namespace SampleApp
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("名前を入力してください:");
            string name = Console.ReadLine();
            Console.WriteLine($"こんにちは、{name}さん!");
        }
    }
}

2. 例外処理


using System;

namespace SampleApp
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("整数を入力してください:");
            try
            {
                int number = int.Parse(Console.ReadLine());
                Console.WriteLine("二乗:" + (number * number));
            }
            catch(Exception e)
            {
                Console.WriteLine("エラー:" + e.Message);
            }
        }
    }
}

3. LINQ を使ったフィルタリング


using System;
using System.Linq;
using System.Collections.Generic;

namespace SampleApp
{
    class Program
    {
        static void Main()
        {
            List numbers = new List { 1, 4, 7, 2, 9, 12 };
            var evenNumbers = numbers.Where(x => x % 2 == 0);

            Console.WriteLine("偶数のみ抽出:");
            foreach(var n in evenNumbers)
            {
                Console.WriteLine(n);
            }
        }
    }
}

4. 非同期処理


using System;
using System.Threading.Tasks;

namespace SampleApp
{
    class Program
    {
        static async Task Main()
        {
            Console.WriteLine("開始");
            await Task.Delay(2000);
            Console.WriteLine("2秒後に終了");
        }
    }
}