0
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#入門 第4章】メソッドの定義と使い方|繰り返し処理をスッキリ整理!

0
Last updated at Posted at 2025-06-06

やっほー、 CSharpTimes の一之瀬シィよ💠
今回はプログラミングの「整理整頓術」こと、 メソッド の使い方をマスターするわよ!


✨ メソッドってなに?

メソッド(=関数)とは、 処理をひとまとめにして名前をつけたもの
同じ処理を何度も書かなくて済む、超便利な仕組みよ!


🧰 メソッドの定義のしかた

// メソッドの定義
void SayHello()
{
    Console.WriteLine("こんにちは!シィよ💠");
}
  • void:戻り値なし
  • SayHello:メソッド名(自分でつけてOK)
  • { } の中に処理を書く

🗣 呼び出してみよう!

class Program
{
    static void Main(string[] args)
    {
        SayHello();  // メソッドを呼び出す
    }

    static void SayHello()
    {
        Console.WriteLine("こんにちは!メソッドからの挨拶よ✨");
    }
}

Main メソッドの外に、 static をつけて定義すればOK!


📦 引数を使ってみよう

メソッドに 値を渡す こともできるわ。

static void Greet(string name)
{
    Console.WriteLine("やっほー、" + name + "ちゃん!");
}

static void Main(string[] args)
{
    Greet("一之瀬");
    Greet("読者さん");
}

🔁 戻り値を返すメソッド

結果を返すには、戻り値の型を指定して return を使うのよ。

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

static void Main(string[] args)
{
    int result = Add(3, 5);
    Console.WriteLine("3 + 5 = " + result);
}

📌 まとめ

  • メソッドは処理のまとまりに名前をつけたもの
  • void :戻り値なし、他に int , string なども使える
  • 引数と戻り値で、再利用性がグッとUPする✨

次回は、 「第5章:クラスとオブジェクト」 よ。
いよいよC#の本領発揮、“オブジェクト指向”の世界に足を踏み入れるわよ💢

0
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
0
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?