728x90
반응형

05. 값 형식과 참조 형식


값 형식

  • System.Object + System.ValueType에서 파생

  • 변수가 직접 값을 저장하는 형

  • 기본 데이터형, 구조체, 열거형

  • 선언 vs 생성(new)

3-17 예제) 일반적 선언과 new를 통해 생성한 객체에 대한 초기값을 출력해 보자.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication18
{
    class Program
    {
        static void Main(string[] args)
        {
            int nVal1 = 12;
            int nVal2 = new int(); // new를 통해서 생성을 하고 있다.
            //object라는 객체를 통해서 상속을 받고 있기 때문에 new를 통해 생성하는 
            // 형태로 사용가능하다.
            Console.WriteLine("{0} {1}", nVal1, nVal2); // 12   0

            char[] test = { 'a', 'b', 'c' };
            string a = new string(test);
            string b = a;
            
            Console.WriteLine("{0} {1}", a, b); // abc abc
        }
    }
}

참조 형식

  • 한 객체를 참조형 변수가 사용할 때 참조형에 의해 내용이 바뀌면 객체에 영향을 준다.

  • class, interface, delegate, 배열, string (참조형에 해당된다)

  • 객체와 참조형 사이의 대입은 객체의 메모리 주소가 복사된다.

예제)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication22
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] Array1 = { 1, 2, 3 }; // 1차원 배열 // 객체생성
            int[] RefArray;  // 참조형 배열 변수
            RefArray = Array1; // 메모리 주소가 넘어간다.
            RefArray[1] = 20;
            Console.WriteLine("{0} {1} {2}", Array1[0], Array1[1], Array1[2]);
            // 1, 20, 3
        }
    }
}

 

06. 정리


  • 기본 데이터형과 CTS 형식을 익혀둔다.

  • 데이터형에 관한 검증 코드를 작성해 보자.

  • 값 형식과 참조 형식(new)의 차이점을 이해하자.

구분 설명
값 형식 기본 데이터형, struct, enum
참조 형식 class, interface, delegate, 배열, string

 

728x90
반응형

'Education > Edu | .net' 카테고리의 다른 글

# 28.2) [C#] 문법11 (Generic)  (0) 2021.02.23
# 28.1) [C#] 문법10  (0) 2021.02.23
# 27) [C#] 문법9 (array)  (0) 2021.02.22
# 26.3) [C#] 문법8 (Property)  (0) 2021.02.19
# 26.2) [C#] 문법7 (interface)  (0) 2021.02.19

+ Recent posts