null
null (C# 참조)
null 키워드는 아무 객체도 가리키지 않는 null 참조를 나타내는 리터럴이에요. 참조형 변수의 기본값이 바로 이 null이죠. 값 형식은 원래 null이 될 수 없는데, nullable 값 형식만 그 예외를 허용해요.
본문
null 참조가 정확히 뭘 의미하는지 예시를 하나 보면 금방 감이 와요. 변수를 선언만 하고 값을 넣지 않으면, 그리고 뚜렷하게 null을 대입하면 어떤 일이 벌어지는지 아래 코드에서 확인해 볼게요.
class Program
{
class MyClass
{
public static void MyMethod() { }
}
static void Main()
{
// Set a breakpoint here to see that mc = null.
// However, the compiler considers it "unassigned."
// and generates a compiler error if you try to
// use the variable.
MyClass mc;
// Now the variable can be used, but...
mc = null;
// ... a method call on a null object raises
// a run-time NullReferenceException.
// Uncomment the following line to see for yourself.
// mc.MyMethod();
// Now mc has a value.
mc = new MyClass();
// You can call its method.
MyClass.MyMethod();
// Set mc to null again. The object it referenced
// is no longer accessible and can now be garbage-collected.
mc = null;
// A null string is not the same as an empty string.
string s = null;
string t = string.Empty; // Logically the same as ""
// Equals applied to any null object returns false.
Console.WriteLine($"t.Equals(s) is {t.Equals(s)}");
// Equality operator also returns false when one
// operand is null.
Console.WriteLine($"Empty string {(s == t ? "equals" : "does not equal")} null string");
// Returns true.
Console.WriteLine($"null == null is {null == null}");
// A value type cannot be null
// int i = null; // Compiler error!
// Use a nullable value type instead:
int? i = null;
// Keep the console window open in debug mode.
}
}
이 예시에서 눈여겨볼 점이 몇 가지 있어요. 선언만 한 참조형 변수는 아무 값도 넣기 전까지 할당되지 않은 상태로 취급돼서 쓰려고 하면 컴파일 오류가 나죠. 그리고 null인 객체에 메서드를 호출하면 NullReferenceException이 실행 시점에 터져요. null 문자열과 빈 문자열(string.Empty)은 서로 달라서 Equals 비교에서도 다르게 나오고, 값 형식은 int i = null;처럼 쓰면 오류가 나니 int? 같은 nullable 값 형식으로 받아야 해요. 코드에 주석으로 잘 적어두었으니 직접 주석을 풀어가며 보면 이해가 훨씬 빨라져요.
C# 언어 사양 문서에는 null 키워드에 대한 공식 문법 사양이 정의되어 있어요.
더 알아보기
- C# keywords — C# 키워드
- Default values of C# types — C# 형식의 기본값
- Nothing (Visual Basic) — Visual Basic의 Nothing