C# 7.0 - Throw Expressions

C# 7.0 – Throw Expressions


Before C# 7.0 it was not possible to throw an exception directly in expression-bodied members. The workaround was to call a method that throws an exception.

Note: You can view all code examples on GitHub. My environment: Visual Studio 2017 and .NET Framework 4.6.1.

        private object ThrowNullArgumentException(string name)
            throw new ArgumentNullException(name);

        private object Example1(object obj) =>
            obj ?? ThrowNullArgumentException(nameof(obj));

This way of throwing exceptions doesn’t look nice. It requires the boilerplate code that doesn’t add any value. Fortunately, the new C# language version comes with an improvement – C# Throw Expressions.

        private object Example2(object obj) =>
            obj ?? throw new ArgumentNullException(nameof(obj));

The same syntax is also acceptable in regular expressions in code blocks.

        private void Example3(IEnumerable<string> names)
            int count =
                names != null
                ? names.Count()
                : throw new ArgumentNullException(nameof(names));



Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.