オンライン C# コンパイラ – ブラウザで C# コードを即実行
ブラウザベースの C# コンパイラでオンラインで C# コードを実行・テストできます。.NET の構文を学んだり、アイデアを試したり、C# アプリケーションを素早くプロトタイプするのに最適です。
🚀 1 合計実行 (1 今月)
📚 今すぐ始めたい人気のC#コース
Loading...
💡 初心者のためのC#基礎ガイド
1. 変数と定数の宣言
C#は強い型付けの変数宣言を使用します。const
はコンパイル時定数に、readonly
は実行時定数に使用します。
int age = 30;
double pi = 3.14159;
char grade = 'A';
string name = "Alice";
bool isActive = true;
// 定数
const int MaxUsers = 100;
const string Company = "CodeUtility";
2. 条件文 (if / switch)
制御フローにはif
、else if
、switch
を使用します。
int x = 2;
if (x == 1)
{
Console.WriteLine("One");
}
else if (x == 2)
{
Console.WriteLine("Two");
}
else
{
Console.WriteLine("Other");
}
switch (x)
{
case 1:
Console.WriteLine("One");
break;
case 2:
Console.WriteLine("Two");
break;
default:
Console.WriteLine("Other");
break;
}
3. ループ
C#はfor
、while
、foreach
ループをサポートしています。
for (int i = 0; i < 3; i++)
{
Console.WriteLine(i);
}
int n = 3;
while (n > 0)
{
Console.WriteLine(n);
n--;
}
4. 配列
配列は同じ型の要素を固定サイズで格納します。
int[] numbers = { 10, 20, 30 };
Console.WriteLine(numbers[1]);
5. リスト操作
動的コレクションにはList<T>
を使用します。
List<int> nums = new List<int> { 1, 2, 3 };
nums.Add(4);
nums.Remove(2);
foreach (int n in nums)
{
Console.Write(n + " ");
}
6. コンソール入出力
基本的な入出力にはConsole.WriteLine
とConsole.ReadLine
を使用します。
Console.Write("名前を入力してください: ");
string name = Console.ReadLine();
Console.WriteLine($"こんにちは, {name}!");
7. 関数
メソッドは戻り値の型、名前、パラメータを使用して定義します。
int Add(int a, int b)
{
return a + b;
}
Console.WriteLine(Add(3, 4));
8. 辞書
Dictionary<TKey, TValue>
はキーと値のペアを格納します。
Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Alice"] = 30;
Console.WriteLine(ages["Alice"]);
9. 例外処理
実行時エラーはtry
、catch
、finally
を使用して処理します。
try
{
throw new Exception("何かが間違っています");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
10. ファイル入出力
ファイル操作にはFile
とStreamReader/StreamWriter
を使用します。
File.WriteAllText("file.txt", "Hello File");
string text = File.ReadAllText("file.txt");
Console.WriteLine(text);
11. 文字列操作
C#の文字列はLength
、Substring
、Contains
のようなメソッドをサポートしています。
string message = "Hello World";
Console.WriteLine(message.Length);
Console.WriteLine(message.Substring(0, 5));
Console.WriteLine(message.Contains("World"));
12. クラスとオブジェクト
C#はクラスとオブジェクトを通じてオブジェクト指向プログラミングをサポートしています。
class Person
{
public string Name;
public Person(string name) => Name = name;
public void Greet() => Console.WriteLine($"Hi, I'm {Name}");
}
Person p = new Person("Alice");
p.Greet();