Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

throwing an exception if an object is null

I've recently discovered that:

if (Foo() != null)    
   { mymethod(); }

can be rewritten as

Foo?.mymethod()

Can the following be rewritten in a similar fashion?

if (Foo == null)
{ throw new Exception()}
like image 837
Alex Gordon Avatar asked Feb 17 '16 23:02

Alex Gordon


People also ask

How do you throw an exception if an object is null?

ThrowIfNull(Void*, String) Throws an ArgumentNullException if argument is null .

How do you throw an exception to null in Java?

In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when program attempts to use an object reference that has the null value. These can be: Invoking a method from a null object.

Should I return null or throw exception?

Only throw an exception if it is truly an error. If it is expected behavior for the object to not exist, return the null. Otherwise it is a matter of preference. It certainly shouldn't be a matter of preference.

What is null reference exception?

A NullReferenceException happens when you try to access a reference variable that isn't referencing any object. If a reference variable isn't referencing an object, then it'll be treated as null .


1 Answers

As of .NET 6 framework you can use the following ThrowIfNull static Method:

void HelloWorld(string argumentOne)
{
    ArgumentNullException.ThrowIfNull(argumentOne);
    Console.WriteLine($"Hello {argumentOne}");
}
like image 109
misanthrop Avatar answered Oct 07 '22 16:10

misanthrop