public void MyMethod(object myObject) { Type objectType = myObject.GetType(); objectType.ThrowIfNull(nameof(myObject)); // continue with using the object }
public void AnotherMethod(object myObject) { Type objectType = myObject?.GetType(); objectType.ThrowIfNull("myObject", "Object is null."); // continue with using the object }This example is similar to the first, but uses the null-conditional operator. If myObject is null, the expression will return null, and the call to ThrowIfNull will throw an exception with the provided message. The System.Type.ThrowIfNull method is included in the System.Runtime.CompilerServices namespace, which is part of the System.Runtime.CompilerServices.Primitives package library.