Share via


null(C# 참조)

업데이트: 2008년 7월

null 키워드는 아무 개체도 참조하지 않는 null 참조를 나타내는 리터럴입니다. null은 참조 형식 변수의 기본값입니다. 일반 값 형식은 null일 수 없습니다. 하지만 C# 2.0에는 nullable 값 형식이 도입되었습니다. nullable 형식(C# 프로그래밍 가이드)을 참조하십시오.

다음 예제에서는 null 키워드의 몇 가지 동작을 보여 줍니다.

class Program
{
    class MyClass
    {
        public void MyMethod() { }
    }

    static void Main(string[] args)
    {
        // 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.
        mc.MyMethod();

        // Set mc to null again. The object it referenced
        // is no longer accsessible 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.
        bool b = (t.Equals(s));
        Console.WriteLine(b);

        // Equality operator also returns false when one
        // operand is null.
        Console.WriteLine("Empty string {0} null string", s == t ? "equals": "does not equal");

        // Returns true.
        Console.WriteLine("null == null is {0}", 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.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();

    }
}

C# 언어 사양

자세한 내용은 C# 언어 사양의 다음 단원을 참조하십시오.

  • 2.4.4.6 null 리터럴

참고 항목

개념

C# 프로그래밍 가이드

참조

C# 키워드

리터럴 키워드(C# 참조)

기타 리소스

C# 참조

기본값 표(C# 참조)

변경 기록

날짜

변경 내용

원인

2008년 7월

코드 예제를 추가했습니다.

콘텐츠 버그 수정