チュートリアル

C#基礎:はじめてのC#

C#入門.NET
広告エリア

はじめに

C#はMicrosoftが開発した言語で、.NETプラットフォーム上で動作します。Windowsアプリ、Webアプリ、ゲーム(Unity)など幅広く使われています。

Hello World

// 従来のスタイル
using System;

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

// C# 9以降のトップレベルステートメント
Console.WriteLine("Hello, World!");

変数とデータ型

値型

// 整数型
byte b = 255;
short s = 32767;
int i = 2147483647;
long l = 9223372036854775807L;

// 符号なし
uint ui = 4294967295U;
ulong ul = 18446744073709551615UL;

// 浮動小数点
float f = 3.14f;
double d = 3.14159265359;
decimal m = 3.14159265359m;  // 高精度(金融計算向け)

// 文字
char c = 'A';

// 真偽値
bool flag = true;

参照型

// 文字列
string name = "太郎";
string greeting = $"こんにちは、{name}さん";  // 文字列補間

// オブジェクト
object obj = 42;
object obj2 = "hello";

// 配列
int[] numbers = { 1, 2, 3, 4, 5 };
string[] fruits = new string[3];

型推論

var name = "太郎";      // string
var age = 25;           // int
var price = 3.14;       // double
var items = new List<string>();  // List<string>

Nullable型

int? nullableInt = null;
int? hasValue = 42;

// null合体演算子
int value = nullableInt ?? 0;

// null条件演算子
string? name = null;
int? length = name?.Length;

// C# 8以降のnull許容参照型
#nullable enable
string nonNullable = "hello";
string? nullable = null;

演算子

// 算術演算子
int a = 10 + 3;   // 13
int b = 10 - 3;   // 7
int c = 10 * 3;   // 30
int d = 10 / 3;   // 3
int e = 10 % 3;   // 1

// 比較演算子
bool eq = (5 == 5);  // true
bool ne = (5 != 3);  // true

// 論理演算子
bool and = true && false;  // false
bool or = true || false;   // true
bool not = !true;          // false

// null合体演算子
string result = name ?? "デフォルト";
name ??= "デフォルト";  // nameがnullなら代入

条件分岐

if文

int age = 20;

if (age >= 20)
{
    Console.WriteLine("成人です");
}
else if (age >= 13)
{
    Console.WriteLine("ティーンエイジャーです");
}
else
{
    Console.WriteLine("子供です");
}

三項演算子

string status = age >= 20 ? "成人" : "未成年";

switch文

int day = 3;

switch (day)
{
    case 1:
        Console.WriteLine("月曜日");
        break;
    case 2:
        Console.WriteLine("火曜日");
        break;
    case 3:
        Console.WriteLine("水曜日");
        break;
    default:
        Console.WriteLine("その他");
        break;
}

// switch式(C# 8以降)
string dayName = day switch
{
    1 => "月曜日",
    2 => "火曜日",
    3 => "水曜日",
    _ => "その他"
};

// パターンマッチング
object obj = 42;
string result = obj switch
{
    int n when n > 0 => "正の整数",
    int n when n < 0 => "負の整数",
    int => "ゼロ",
    string s => $"文字列: {s}",
    _ => "その他"
};

ループ

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

// foreach
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
    Console.WriteLine(num);
}

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

// do-while
do
{
    Console.WriteLine(count);
    count++;
} while (count < 10);

配列とコレクション

// 配列
int[] numbers = { 1, 2, 3, 4, 5 };
int[] arr = new int[5];
arr[0] = 10;

// 多次元配列
int[,] matrix = new int[3, 3];
int[,] matrix2 = { { 1, 2 }, { 3, 4 } };

// List
using System.Collections.Generic;

List<string> fruits = new List<string> { "apple", "banana" };
fruits.Add("orange");
fruits.Remove("apple");
int count = fruits.Count;

// Dictionary
Dictionary<string, int> prices = new Dictionary<string, int>
{
    { "apple", 100 },
    { "banana", 200 }
};
prices["orange"] = 150;
int applePrice = prices["apple"];

文字列操作

string str = "Hello, World!";

// 長さ
int len = str.Length;

// 検索
int index = str.IndexOf("World");
bool contains = str.Contains("Hello");

// 変換
string upper = str.ToUpper();
string lower = str.ToLower();
string replaced = str.Replace("World", "C#");

// 分割・結合
string[] parts = "a,b,c".Split(',');
string joined = string.Join("-", parts);

// フォーマット
string formatted = string.Format("名前: {0}, 年齢: {1}", "太郎", 25);
string interpolated = $"名前: {"太郎"}, 年齢: {25}";

// StringBuilder
using System.Text;
var sb = new StringBuilder();
sb.Append("Hello");
sb.Append(", World!");
string result = sb.ToString();

まとめ

  • C#は.NET上で動作する静的型付け言語
  • varで型推論、?でnull許容型
  • switch式とパターンマッチングが強力
  • List<T>Dictionary<TKey, TValue>がよく使われる

次回はメソッドとクラスについて学びます。

広告エリア