본문 바로가기
C#

class vs struct

by Falto 2023. 5. 18.

이 코드 하나에 class와 struct의 차이가 담겨있다.

using System;

namespace TEST
{
    internal class Person { public int age; }
    internal struct Apple { public int brix; }

    internal class Program
    {
        private static void Main(string[] args)
        {
            Person a = new Person { age = 10 };
            Person b = a;
            b.age = 15;
            Console.WriteLine(a.age);

            Apple c = new Apple { brix = 20 };
            Apple d = c;
            d.brix = 40;
            Console.WriteLine(c.brix);
        }
    }
}

출력은

15

20

이다.

reference를 복사하는가 value를 복사하는가의 차이다.

        private static void Main(string[] args)
        {
            Person a = new Person { age = 10 };
            Person b = a;
            Console.WriteLine(object.ReferenceEquals(a,b));

            Apple c = new Apple { brix = 20 };
            Apple d = c;
            Console.WriteLine(object.ReferenceEquals(c,d));
        }

출력은

True

False

이다.

 

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

lock  (1) 2023.07.02
파일 읽고 쓰기의 비효율성  (0) 2023.05.27
[C# Windows] System.IO.Path.GetTempPath 쓰지 마라.  (0) 2023.05.09
garbage collect의 함정  (0) 2023.03.25
개발자와 사용자의 관점 차이  (0) 2023.03.14

댓글