Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking C# new() initialisation for null?

I've found this piece of code on Koders:

private ServiceProvider SiteServiceProvider
{
    get
    {
        if (serviceProvider == null)
        {
            serviceProvider = new ServiceProvider(site as VSOLE.IServiceProvider);
            Debug.Assert(serviceProvider != null, "Unable to get ServiceProvider from site object.");
        }
        return serviceProvider;
    }
}

I'm wondering, is there any possible way the Debug.Assert(serviceProvider != null could trigger? I'm under the impression that new could only be aborted by an exception, in which case the assert would never be reached.

like image 387
David Schmitt Avatar asked Dec 16 '08 13:12

David Schmitt


People also ask

What is check in C?

Learn how to check a character value in C We have access to several useful checks: isalnum() checks if a character is alphanumeric. isalpha() checks if a character is alphabetic. iscntrl() checks if a character is a control character. isdigit() checks if a character is a digit.

What is a better C?

For most people, C++ is the better choice. It has more features, more applications, and for most people, learning C++ is easier. C is still relevant, and learning to program in C can improve how you program in C++. Neither language is a bad choice, and both have realistic career applications.

What are the C standards?

What is the C programming language standard? It is the standard way defined for the compiler creators about the compilation of the code. The latest C standard was released in June 2018 which is ISO/IEC 9899:2018 also known as the C11.

Is C easy for beginners?

And I would say it's not the easiest language, because C is a rather low level programming language. Today, C is widely used in embedded devices, and it powers most of the Internet servers, which are built using Linux. The Linux kernel is built using C, and this also means that C powers the core of all Android devices.


2 Answers

It's possible that the ServiceProvider overrides the !=/== operator, so that for an invalid state the comparison to null returns true.

Looks strange anyway.

like image 63
arul Avatar answered Oct 20 '22 12:10

arul


I would expect that "test for null" pattern more if it was a factory method - i.e.

SomeType provider = SomeFactory.CreateProvider();
if(provider == null) // damn!! no factory implementation loaded...
{ etc }

There is one other case worth knowing about, but which doesn't apply here (since we know the type we are creating)... Nullable<T>; this is mainly an issue with generics:

static void Test<T>() where T : new()
{
    T x = new T();
    if (x == null) Console.WriteLine("wtf?");
}
static void Main()
{
    Test<int?>();
}

This is covered more here.

like image 34
Marc Gravell Avatar answered Oct 20 '22 13:10

Marc Gravell