LoginSignup
7
6

More than 5 years have passed since last update.

C#のC/C++のdefine定数の定義方法

Last updated at Posted at 2015-08-17

C#のC/C++のdefine定数の定義方法

CもしくはC++の場合

C/C++
#define MAX_STRING 256
#define ERROR_MSG "error!"

C#の場合変数を静的なクラスにstatic readonlyもしくは※ constで定義することで、C/C++のdefine定数のように扱うことができる。

※2016/04/13追記
readonly変数は初期化子またはコンストラクタ内で初期化できます。
defineは静的に値が決まっていますが、readonly変数は実行時に動的に値が設定されます。
そのため、C/C++のdefine定数とreadonly変数は同一のものとは言えません。

C#
public static class Define
{
    // static readonlyの場合
    public static readonly int ST_MAX_STRING = 256;
    public static readonly string ST_ERROR_MSG = "error!"; 
    // constの場合
    public const int CS_MAX_STRING = 256;
    public const string CS_ERROR_MSG = "error!";
}

アクセスするときは以下のようにする。

C#
public class Example
{
    public static void Main()
    {
        // static readonlyの定義
        var stVal = Define.ST_MAX_STRING;
        var stMsg = Define.ST_ERROR_MSG;
        // constの定義
        var csVal = Define.CS_MAX_STRING;
        var csMsg = Define.CS_ERROR_MSG;
    }
}

参考

https://msdn.microsoft.com/ja-jp/library/bb397677.aspx

7
6
1

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