CSharp · Console
using System;
using System.Runtime.CompilerServices;
#nullable enable
public static class NullExtensions
{
public static T ThrowIfNull<T>(this T? argument, string? message = default, [CallerArgumentExpression("argument")] string? paramName = default)
where T : struct
{
if (argument is null)
throw new ArgumentNullException(paramName, message);
return (T)argument;
}
public static string ThrowIfNull(this string? argument, string? message = default, [CallerArgumentExpression("argument")] string? paramName = default)
{
if (argument is null)
throw new ArgumentNullException(paramName, message);
return argument;
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
string? foo = "foo";
string nonNullableFoo = foo.ThrowIfNull(); // success from "string?" to "string"
Console.WriteLine(nonNullableFoo);
bool? baz = true;
bool nonNullableBaz = baz.ThrowIfNull(); // success from "string?" to "string"
Console.WriteLine(nonNullableFoo);
int? bar = 2;
int nonNullableBar = bar.ThrowIfNull(); // error: Cannot implicitly convert type 'int?' to 'int'
Console.WriteLine(nonNullableBar);
}
}