throwing an exception if an object is null
As of .NET 6, you can use the ArgumentNullException.ThrowIfNull()
static method:
void HelloWorld(string argumentOne)
{
ArgumentNullException.ThrowIfNull(argumentOne);
Console.WriteLine($"Hello {argumentOne}");
}
Yes, as of C# 7 you can use Throw Expressions
var firstName = name ?? throw new ArgumentNullException("Mandatory parameter", nameof(name));
Source
There is no similar fashion syntax in C# 6.
However, if you want you can simplify null check by using an extension methods...
public static void ThrowIfNull(this object obj)
{
if (obj == null)
throw new Exception();
}
usage
foo.ThrowIfNull();
Or improvement it to display null object name.
public static void ThrowIfNull(this object obj, string objName)
{
if (obj == null)
throw new Exception(string.Format("{0} is null.", objName));
}
foo.ThrowIfNull("foo");