전체 글
[C#] Boxing / Unboxing (2)
1. 핵심 정리 using System; class Program { static void Main() { Console.WriteLine(10 < 20); // true Console.WriteLine(10.CompareTo(20)); // -1 Console.WriteLine(10.CompareTo(10)); // 0 Console.WriteLine(10.CompareTo(5)); // 1 string s1 = "AAA"; string s2 = "BBB"; Console.WriteLine(s1 < s2); Console.WriteLine(s1.CompareTo(s2)); // -1 } } ① 객체의 크기를 비교하는 방법 C#에서 객체의 크기를 비교하는 방법은 관계연산자와 CompareTo메소드가 있다..
[C#] Boxing / Unboxing (1)
1. 핵심 정리 using System; class Program { static void Main() { int[] a1 = {1, 2, 3}; object o1 = a1; int[] a2 = (int[])o1; Console.WriteLine(a2[0]); } } 먼저 5~9번 라인을 보자. 먼저 int형의 배열을 만들었다. 배열은 C#에서 참조타입이므로 Heap에 생성되었을 것이다. 다음 object는 모든 타입의 기반 타입이므로 o1도 a1과 같은 Heap을 바라볼 것이다. 마지막으로 위의 obejct타입을 다시 배열로 캐스팅하여 담을 수도 있다. 그림으로 나타내면 아래와 같다. 모두 같은 메모리를 바라보기에 만약 중간에서 a1이나 o1의 값을 바꿔도 a2를 출력해보면 바뀐 값으로 출력되는 것을 ..
[C#] casting
1. casting using System; class Program { static void Main() { int n = 3; double d = 3.4; d = n; // int => double - 데이터 손실 없음 n = d; // double => int - 데이터 손실 방생 error n = (int)d; } } ① 캐스팅 규칙 => 데이터 손실이 발생하지 않은 경우 암시적 형 변환 될 수 있다. => 데이터 손실이 발생하는 경우 명시적 캐스팅을 해야 한다. 2. is, as using System; class Animal { } class Dog : Animal { public void Cry() { Console.WriteLine("Dog Cry"); } } class Program { ..
[C#] Elvis Operator (?, ??) 연산자
1. 널 조건부 연산자 (null conditional operator) using System; class Car { public int color = 10; public void Go() { Console.WriteLine("Go"); } } class Program { public static Car CreateCar(int speed) { if(speed > 200) return null; return new Car(); } public static void Main() { Car c = CreateCar(100); c.Go(); } } Car라는 클래스를 만들고 테스트를 위해 color와 Go라는 메소드를 만들었다. 그리고 밑에 CreateCar라는 메소드를 만들었다. 여기선 Car라는 객체를 ..
[C#] Nullable<T>
1. 핵심 정리 using System; class Program { public static void Main() { // string : reference type string s1 = "Hello"; // 객체 생성 string s2 = null; // 객체 없음. // int : value type int n1 = 10; // 객체 생성 int n2 = ?; // 값이 없음을 표현하고 싶을 땐? } } ① Reference Type => null을 사용하면 객체 없음 상태를 표현할 수 있다. ② Value Type => 값 없음을 표현할 수 없다. ③ Nullable => Value Type에 값 없음을 추가한 것 => Nullable = int + bool => null을 사용할 수 있다. us..
[C#] 동등성 (Equality)
1. 참조 타입(reference type)의 동등성(Equality) using System; class Point { private int x = 0; private int y = 0; public Point(int xPos, int yPos) { x = xPos; y = yPos; } } class Program { static void Main() { Point p1 = new Point(1, 1); Point p2 = p1; Point p3 = new Point(1, 1); // 방법1. == 연산자 사용 // 기본 동작 : 참조(주소)가 동일한가 ? Console.WirteLine(p1 == p2); // true Console.WriteLine(p1 == p3); // false // 방법2..