Search code examples
c#.netvisual-studionulloperators

Throw an exception if an object is null


I've recently discovered that this:

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() }

Solution

  • I don't know why you would..

    public Exception GetException(object instance)
    {
        return (instance == null) ? new ArgumentNullException() : new ArgumentException();
    }
    
    public void Main()
    {
        object something = null;
        throw GetException(something);
    }