0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

constとは?定数について

Last updated at Posted at 2022-02-02

初心者の勉強記録兼忘備録です。

constとは何か

変数宣言をする際、アクセス修飾子と型の間に"const"をつけることで値が定数(固定値)となり、宣言後はその値を変更することができない。

なぜ必要なのか

プログラムを書く上で変化しない値をいろいろな場所で何度も使いたいことがある。constを使用することにより、他クラスでもこの定数が使用できる。
他クラスで使用する場合はstaticと同様にクラス名にドットを付けることで使用可能。

使用例

ExampleA.cs
public class ExampleA : MonoBehaviour
{
  //定数
  private const int ValueA = 100
  private const string ValueB = "abcde"

  //変数
  private int ValueC = 100;
  private string ValueD = "abcdef";
}
ExampleB.cs
public class ExampleB : MonoBehaviour
{
  public void Start()
 {
  //ExampleAクラスからValueAを使いたい場合
  Debug.Log(ExampleA.ValueA); //ValueAの値100がコンソールに出力される
 }
}

参考記事
定数 - 未確認飛行C
C#初心者のための基礎!#3値の扱い方。変数と定数をわかりやすく解説!

間違えている場合は遠慮なくご指摘ください。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?