Używanie instrukcji z obiektem null

Czy używanie instrukcji using na (potencjalnie) obiekcie null jest bezpieczne?
Rozważ następujący przykład:

class Test {
    IDisposable GetObject(string name) {
        // returns null if not found
    }

    void DoSomething() {
        using (IDisposable x = GetObject("invalid name")) {
            if (x != null) {
                 // etc...
            }
        }
    }
}

Czy jest zagwarantowane, że Dispose zostanie wywołane tylko wtedy, gdy obiekt nie będzie null, a ja nie otrzymam NullReferenceException?

Author: BartoszKP, 2010-03-26

5 answers

TAK, Dispose() jest wywoływane tylko na obiektach innych niż null:

Http://msdn.microsoft.com/en-us/library/yh598w02.aspx

 135
Author: reko_t,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-04 18:40:49

Rozszerzenie dla using sprawdza, czy obiekt nie jest null przed wywołaniem Dispose na nim, więc tak, jest bezpieczne.

W Twoim przypadku dostaniesz coś w stylu:

IDisposable x = GetObject("invalid name");
try
{
    // etc...
}
finally
{
    if(x != null)
    {
        x.Dispose();
    }
}
 27
Author: João Angelo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-22 17:22:32

Powinno być ok z tym:

using ((IDisposable)null) { }

Tutaj nie ma wyjątku.

Uwaga na marginesie: nie myl tego z foreach i IEnumerable, gdzie zostanie wyrzucony wyjątek.

 10
Author: Darin Dimitrov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-03-26 11:25:36

Tak, przed usunięciem Referencja będzie sprawdzana null. Możesz sprawdzić siebie, wyświetlając swój kod W reflektorze.

 0
Author: oli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-03-26 11:27:03

Nie otrzymasz wyjątku null reference, jak z mojego doświadczenia. Zostanie po prostu zignorowany.

 -2
Author: malay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-03-26 11:26:33