This project is read-only.

Extending the null-coalescing operator to support throwing exceptions

Topics: C# Language Design
Mar 15, 2015 at 5:27 PM
Edited Mar 15, 2015 at 5:31 PM
Here is some example code that I hope will explain the use case
                static IEnumerable<Order> GetCustomerOrders(int customerId)
        {
            //if no orders are found for the customer Id provided, then throw a specific Business Exception
            var orders = new List<Order>(); // Here you'd query the DB and return a null if no orders found


            if (orders == null)
                throw new Exception("No orders found for Customer with Id:" + customerId.ToString());

            return orders;

            // instead of the above 2 lines, I'd like to do this
            return orders ?? throw new Exception("No orders found for Customer with Id:" + customerId.ToString());
        }
I'd like to be able to write code like that shown in the last line in the method above
Mar 15, 2015 at 8:16 PM
  1. Roslyn has moved to GitHub, so any discussion belongs on issues there, not here.
  2. There already is a proposal that would allow you to write code like this.