第8講 メソッド(2)
第1話 C#の魔法!
C#では変数そのものすなわち箱そのものは渡すことが出来ません。
メソッド内で宣言した変数のスコープ(適用範囲)はメソッド内に限定されているからです。
引数で渡していたのは、箱そのものではなくあくまで箱の中身である値です。
ですが、仕事を依頼したメソッドに、
箱の中身を変更してもらいたいときがあります。
箱を渡していないのに、
箱の中身を変えるなんてこと出来るのでしょうか。
配列は添え字付き変数でした。
     int[] a = new int[n];
と宣言すると、n 個の変数が用意されるのでした。
具体的には、
a[0],a[1],a[2],・・・,a[n-1]
です。最後がnではなくn-1なのでしたね。
n を配列の要素数といいます。
     int[] a = new int[1];
と宣言すれば、要素数1の配列ですから、実質『変数を宣言した=箱を用意した』のと同じです。
ところで、箱そのものは渡せないのに、
箱の中身を変えてもらう魔法にような方法があるのでしょうか。
それがあるんです。
実際にやってみましょう。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace メソッドに配列を渡す
{
  class Program
  {
    static void Main[string[] args]
    {
      int[] a = new int[1];
      a[0] = 3;
      Console.WriteLine["a[0]={0:d} ", a[0]];
      f[a];
      Console.WriteLine["a[0]={0:d} ", a[0]];
    }
    static void f[int[] a]
    {
      a[0] = 5;
    }
  }
}
実行画面
a[0]=3
a[0]=5
『なんだ!?結局
    f [a]
で箱を渡しているではないか?』
と思いになるかもしれませんが、
第5講第8話のコードを少し変えて、
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace メソッドに配列を渡す
{
  class Program
  {
    static void Main(string[] args)
    {
      int a ;
      a = 3;
      Console.WriteLine("a={0:d} ", a);
      f(a);
      Console.WriteLine("a={0:d} ", a);
    }
    static void f(int a)
    {
      a = 5;
    }
  }
}
とすると実行結果は
a = 3
a = 3
です。
箱そのものは決して渡せないのです。
2つのコードの主要部分を並べてみると、
    static void Main[string[] args]
    {
      int[] a = new int[1];
      a[0] = 3;
      Console.WriteLine["a[0]={0:d} ", a[0]];
      f[a];
      Console.WriteLine["a[0]={0:d} ", a[0]];
    }
    static void f[int[] a]
    {
      a[0] = 5;
    }
     static void Main(string[] args)
    {
      int a ;
      a = 3;
      Console.WriteLine("a={0:d} ", a);
      f(a);
      Console.WriteLine("a={0:d} ", a);
    }
    static void f(int a)
    {
      a = 5;
    }
と大変そっくりですが、結果は異なっています。
下のコードが箱そのもの=変数そのものを渡すことが出来ないことを示しています。
上のコードでも決して箱そのものは渡していません。
でも、
a[0]=3
a[0]=5
です。
いったいどういうことなんでしょうか。
