コンストラクタ

プログラミングC# 第6版 3.2.3


クラス名と同じ名称でメソッドを作るとコンストラクタになります。

using System;

class CSample {
    public CSample (string strval) {
        str = strval;
    }
    public string str {
        get;
        private set;
    }
}

class Program {
    static void Main () {
        CSample obj = new CSample("hello");
        Console.WriteLine(obj.str);
    }
}
$ main
hello

これはもうC++とほぼ同じですね。戻り値を何も書かないと言う部分も一緒です。