본문 바로가기
개발/C#

상수와 열거 형식

by 민돌이2 2019. 1. 30.

상수와 열거 형식

상수(constants)와 열거 형식(Enumerator)은 변수와는 달리 안에 담긴 데이터가 절대 변하지 않는다.

프로그래머나 사용자가 실수로 변수의 값을 바꿔 에러 방지

1.상수 : const

데이터 형식앞에 const키워드가 위치하고 상수가 가져야하는 데이터를 반드시 대입해야 한다.

형식

 const 자료형 상수명 = 값; 


 const int a = 3;

 const double b =3.14;

 const string c = "abcdef"; 



2.열거 형식 : enum

정수 계열(byte, sbyte, short, ushort, int , uint, long ,ulong)만 사용 가능

기반자료형을 생략할 경우 int를 사용한다.


형식

enum 열거 형식명 : 기반자료형 { 상수1, 상수2, 상수3 ,.... }

enum DialogResult : byte { YES, NO, CANCEL, CONFRIM, OK}


선언된 순서에 따라 1씩 증가된 값을 컴파일러가 자동으로 할당한다.

using System;

using static System.Console;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace PracticeCS

{

    class Program

    {

        enum Test : byte { YES, NO, CANCEL, CONFIRM, OK };

        static void Main(string[] args)

        {

            WriteLine(Test.YES);

            WriteLine((byte)Test.YES);

            WriteLine((byte)Test.NO);

            WriteLine((byte)Test.CANCEL);

            WriteLine((byte)Test.CONFIRM);

            WriteLine((byte)Test.OK);


        }

    }

}

 


3.Nullable 형식

어떠 값도 가지지 않는 변수가 필요할 때 0이 아닌 비어 있는 변수, 즉 null상태


형식

데이터형식? 변수이름 = null; 

int? a = null;

float? b= null;

double? c = null; 


Nullable형식은 HasValue와 Value 두 가지 속성을 갖는다.

HasValue는 변수가 값을 갖고 있는지 없는지, Value는 변수의 값을 나타낸다.

using System;

using static System.Console;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace PracticeCS

{

    class Program

    {

        enum Test : byte { YES, NO, CANCEL, CONFIRM, OK };

        static void Main(string[] args)

        {

            int? a=null;

            WriteLine(a.HasValue);

            WriteLine(a != null);


            a = 3;

            WriteLine(a.HasValue);

            WriteLine(a != null);

            WriteLine(a.Value);

        }

    }

}

 


728x90

'개발 > C#' 카테고리의 다른 글

문자열다루기2  (0) 2019.02.02
문자열 다루기  (0) 2019.01.31
[C#] 제네릭과 컬렉션  (0) 2018.11.29
[C#]형변환  (0) 2018.11.28
[C#]네임스페이스  (0) 2018.11.16

댓글