LoginSignup
7
6

More than 5 years have passed since last update.

constとreadonly

Last updated at Posted at 2015-01-25

C#の定数は
コンパイル時定数と実行時定数の2つある

コンパイル時定数

private const int hoge = 1;

実行時定数

private readonly int hogehoge =  2;

コンパイル時定数
実行時定数よりもすこし高速
staticがついていなくてもstaticであるかのように扱える

実行時定数
コンストラクタで値が決定されるので生成されたインスタンス毎に固有の値を持てる
new演算子により生成されるオブジェクトを定義できる。

//使える
public readonly System.DateTime readonlyDateTime = new System.DateTime ();
//使えない
public const System.DateTime constDateTime = new System.DateTime ();

constはswitchのcaseに使えてreadonlyは使えない

enum HogeHoge
{
    AAAA,BBBB,CCCC
}

const HogeHoge aaaa = HogeHoge.AAAA;
readonly HogeHoge bbbb = HogeHoge.BBBB;

void Hoge()
{
    HogeHoge cccc = HogeHoge.CCCC;
    switch(cccc)
    {
        //使える
        case aaaa:
        break;

        //使えない
        case bbbb:
        break;

     case HogeHoge.CCCC:
        break;
    }
}
7
6
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
7
6