Best way to check for null parameters (Guard Clauses)

后端 未结 10 1806
北荒
北荒 2021-01-31 16:45

For example, you usually don\'t want parameters in a constructor to be null, so it\'s very normal to see some thing like

if (someArg == null)
{
    throw new Arg         


        
10条回答
  •  南方客
    南方客 (楼主)
    2021-01-31 17:35

    The simplest approach I've found is inspired by Dapper's use of anonymous types. I've written a Guard class that uses anonymous types to get name of properties. The guard itself is the following

        public class Guard
        {
            public static void ThrowIfNull(object param) 
            {
                var props = param.GetType().GetProperties();
                foreach (var prop in props) 
                {
                    var name = prop.Name;
                    var val = prop.GetValue(param, null);
    
                    _ = val ?? throw new ArgumentNullException(name);
                }
            }
        }
    

    The use is then

    ...
            public void Method(string someValue, string otherValue)
            {
                Guard.ThrowIfNull(new { someValue, otherValue }); 
            }
    ...
    

    When the ArgumentNullException is thrown and the correctly named property will be displayed.

提交回复
热议问题