티스토리 뷰

LANGUAGE/C#

[C#] 기본 문법

진심스테이크 2018. 6. 13. 11:24

연산자 : +, -, !, ~, ++, -- 등

- ! (not)은 bool형에만 사용

ex) !-1 //0

namespace _0613
{
    class Program
    {
        static void Main(string[] args)
        {
            bool bFlag = false;
            Console.WriteLine("{0} {1} {2}", !bFlag, !true, !false); //true false true
        }
    }
}

 

산술 연산자 : *, /, %, -, +

- string에서 +는 문자열 연결

- 정수/부동 + "문자열" = "문자열"

namespace _0613
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "3" + ".14";
            Console.WriteLine(+5); //숫자 양 5
            Console.WriteLine(5 + 5); //숫자 10
            Console.WriteLine(5 + .5); //숫자 5.5
            Console.WriteLine("5" + "5"); //문자열 55
            Console.WriteLine(5.01f + "5"); //문자열5.015
            Console.WriteLine(3.14f + "5"); //문자열 3.145
            Console.WriteLine(str); //문자열 3,14
        }
    }
}

 

Shift 연산자와 관계 연산자 : <<, >>, >=. <=, >, ==, !=

- 결과는 true와 false

 

 

is 연산자

- 형식 호환을 조사

- 기본 형태

  '변수 is '클래스형 or 데이터형'

- 결과는 true와 flase

- boxing/unboxing 변환, 참조 변환에서 사용

namespace _0613
{
    class Program
    {
        static void Main(string[] args)
        {
            int value = 10;
            if (value is float)
                Console.WriteLine("호환됨");
            else
                Console.WriteLine("호환 안됨");
            //호환 안됨

            if (value is object) //boxing 호환
                Console.WriteLine("호환됨");
            else
                Console.WriteLine("호환 안됨");
            //호환됨

            object obj = value;
            if (obj is int) //unboxing
                Console.WriteLine("호환됨");
            else
                Console.WriteLine("호환 안됨");
            //호환됨
        }
    }
}

 

as 연산자

- 형변환과 변환 조사

- 캐스트 연산자의 역할과 불변환은 null 리턴

- 참조, boxing, unboxing, null형에 사용

- 기본 형태

  결과형 = 참조형, unboxing, boxing as 변환형

namespace _0613
{

    class A
    {

    }

    class B
    {

    }

    class Program
    {
        static void Main(string[] args)
        {
            string str = "123";
            object obj = str; //boxing
            string str2 = obj as string; //boxing된 내용을 string으로 변환
            Console.WriteLine(str2);

            A test = new A();
            object obj1 = test;
            B test2 = obj1 as B; //A를 B로 참조 하지 못함 - null
            if (test2 == null)
                Console.WriteLine("형 변환 실패");
            else
                Console.WriteLine("형 변환 성공");
            //형 변환 실패
        }
    }
}

 

 

비트 연산자와 논리 연산자 : &, ^, |, &&, ||, ?, :

 

 

null 병합 연산자 : ??

- nullable 형일때, null인지 아닌지 조사

ex) C = A ?? B

    //A가 null이 아니면 A를 C에 대입

    //A가 null이면 B를 C에 대입

namespace _0613
{
    class Program
    {
        static void Main(string[] args)
        {
            int? x = null; //nullable 형식, null 저장 가능
            int y = x ?? -1; //x가 null이면 y에 -1 대입
            Console.WriteLine(y); //-1
            x = 10;
            y = x ?? -1;
            Console.WriteLine(y); //10
        }
    }
}

 


 

제어문

 

선택문

- if ~ else

namespace _0613
{
    class Program
    {
        static void Main(string[] args)
        {
            int num = 10;
            if (true) //true - 항상 실행
                Console.WriteLine("Hello World");
            else
                Console.WriteLine("C# Programming");
           
        }
    }
}

 

- switch, case

  -> 정수, 문자상수 (ASCII), 문자열

  -> 모든 case와 default에는 break가 반드시 있어야함

namespace _0613
{
    class Program
    {
        static void Main(string[] args)
        {
            int num = 1;
            switch (num)
            {
                case 1:
                    Console.WriteLine("1");
                    break;
                case 2:
                    Console.WriteLine("2");
                    break;
            }
        }
    }
}
 
namespace _0613
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "yes";
            switch (str)
            {
                case "no":
                    Console.WriteLine("no");
                    break;
                case "yes":
                    Console.WriteLine("yes");
                    break;
            }
        }
    }
}
 
namespace _0613
{
    class Program
    {
        static void Main(string[] args)
        {
            char c = 'a';
            switch (c)
            {
                case 'a':
                    Console.WriteLine("a");
                    break;
                case 'b':
                    Console.WriteLine("b");
                    break;
            }
        }
    }
}

 

 

반복문

- for

  -> for(;;) : 무한반복

- while, do ~ while

  -> while(true)

- foreach : 처음부터 끝까지 순차적으로 값을 반복하여 읽는 역할

  -> 읽기 전용

  -> 기본 형태

      foreach( 데이터형 변수 in 배열명(컬렉션명))

      {

   

      }

 

namespace _0613
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = { 1, 2, 3, 4 };
            foreach (int value in arr)
            {
                Console.WriteLine(value);
            }
        }
    }
}
 
namespace _0613
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList list = new ArrayList();
            list.Add(1);
            list.Add(2);
            list.Add(3);

            foreach (int m in list)
                Console.WriteLine(m);
        }
    }
}

 

 

점프문 : goto, continue, return, break

 

 


 

예외 처리문

 

- 예외 : 런타임 시에 발생할 수 있는 오류

- 다중 가능

- 처리 방법

1. if ~ else

2. try ~ catch

- 기본 형태

  try

  {

    //예외가 발생할 수 있는 코드

  } catch ( 예외처리객체 e )

  { 

   //예외 처리

  }

- System.Exception 파생 객체

  OverFlowException, FormatException, DivideByZeroException, FileNotFoundException, IndexOutOfRangeException

namespace _0613
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = { 1, 2, 3 };
            try
            {
                array[3] = 10;
            }
            catch (IndexOutOfRangeException e)
            {
                Console.WriteLine("배일 인덱스 배열 발생");
                Console.WriteLine(e.ToString());
                array[2] = 10;
            }
            for(int i = 0; i < array.Length; i++)
                Console.WriteLine("{0}", array[i]);
        }
    }
}

 

- try문 안에서 초기화한 변수를 try문 밖에서 사용할 수 없다

namespace _0613
{
    class Program
    {
        static void Main(string[] args)
        {
            //int m; //에러
            int m = 0; //초기화를 하면 에러가 안뜸
            try
            {
                m = 12;
                Console.WriteLine("try문 출력 : {0}", m);
            }
            catch
            {
                Console.WriteLine("예외발생");
            }
            Console.WriteLine("try문 밖에서 변수 출력 : {0}", m);
        }
    }
}

 

3. try ~ finally

- finally : 예외 발생과 상관없이 항상 실행되는 구문

- 예외적인 상황이 발생했을 때 finally 처리

namespace _0613
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = { 1, 2, 3 };
            try
            {
                Console.WriteLine("try문에서 예외 발생");
                array[3] = 10;
            }
            finally //무조건 실행되는 구문
            {
                Console.WriteLine("finally 구문");
            }

            foreach (var m in array)
                Console.Write("{0} ", m);
        }
    }
}

 

- 예외상황이 발생하지 않았을 때 finally 처리

#예외와 상관없이 실행

namespace _0613
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
            try
            {
                i = 12;
            }
            finally
            {
                i = 100;
                Console.WriteLine("finally 문 i 값 : {0}", i); //100
            }

            i = 200;
            Console.WriteLine("try finally문 밖에서 실행 i 값 : {0}", i); //200
        }
    }
}

 

 

 throw

- 예외 상황을 임의로 발생시켜줌

- System.Exception 파생된 객체만 사용

- try문과 그 외에서 사용 가능

namespace _0613
{
    class Program
    {

        static int getNumber(int index)
        {
            int[] nums = { 300, 600, 900 };
            if (index >= nums.Length)
            {
                throw new IndexOutOfRangeException();
            }
            return nums[index];
        }
        static void Main(string[] args)
        {
            int result = getNumber(3);
        }
    }
}

 

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

[C#] 파일 입출력  (0) 2018.06.14
[C#] 배열  (0) 2018.06.14
[C#] 값 형식 / 참조 형식  (0) 2018.06.12
[C#] 사용자 지정형  (0) 2018.06.12
[C#] 표준 입력  (0) 2018.06.12
댓글