C# if-null-then-null expression

前端 未结 6 1939
误落风尘
误落风尘 2020-12-01 02:56

Just for curiosity/convenience: C# provides two cool conditional expression features I know of:

string trimmed = (input == null) ? null : input.Trim();
         


        
6条回答
  •  难免孤独
    2020-12-01 03:24

    There's nothing built-in, but you could wrap it all up in an extension method if you wanted (although I probably wouldn't bother).

    For this specific example:

    string trimmed = input.NullSafeTrim();
    
    // ...
    
    public static class StringExtensions
    {
        public static string NullSafeTrim(this string source)
        {
            if (source == null)
                return source;    // or return an empty string if you prefer
    
            return source.Trim();
        }
    }
    

    Or a more general-purpose version:

    string trimmed = input.IfNotNull(s => s.Trim());
    
    // ...
    
    public static class YourExtensions
    {
        public static TResult IfNotNull(
            this TSource source, Func func)
        {
            if (func == null)
                throw new ArgumentNullException("func");
    
            if (source == null)
                return source;
    
            return func(source);
        }
    }
    

提交回复
热议问题