Method call if not null in C#

后端 未结 11 1102
情深已故
情深已故 2020-12-12 13:05

Is it possible to somehow shorten this statement?

if (obj != null)
    obj.SomeMethod();

because I happen to write this a lot and it gets p

相关标签:
11条回答
  • 2020-12-12 13:36

    A quick extension method:

        public static void IfNotNull<T>(this T obj, Action<T> action, Action actionIfNull = null) where T : class {
            if(obj != null) {
                action(obj);
            } else if ( actionIfNull != null ) {
                actionIfNull();
            }
        }
    

    example:

      string str = null;
      str.IfNotNull(s => Console.Write(s.Length));
      str.IfNotNull(s => Console.Write(s.Length), () => Console.Write("null"));
    

    or alternatively:

        public static TR IfNotNull<T, TR>(this T obj, Func<T, TR> func, Func<TR> ifNull = null) where T : class {
            return obj != null ? func(obj) : (ifNull != null ? ifNull() : default(TR));
        }
    

    example:

        string str = null;
        Console.Write(str.IfNotNull(s => s.Length.ToString());
        Console.Write(str.IfNotNull(s => s.Length.ToString(), () =>  "null"));
    
    0 讨论(0)
  • 2020-12-12 13:37

    Yes, in C# 6.0 -- https://msdn.microsoft.com/en-us/magazine/dn802602.aspx.

    object?.SomeMethod()
    
    0 讨论(0)
  • 2020-12-12 13:38

    I agree with the answer by Kenny Eliasson. Go with Extension methods. Here is a brief overview of extension methods and your required IfNotNull method.

    Extension Methods ( IfNotNull method )

    0 讨论(0)
  • There is a little-known null operator in C# for this, ??. May be helpful:

    http://weblogs.asp.net/scottgu/archive/2007/09/20/the-new-c-null-coalescing-operator-and-using-it-with-linq.aspx

    0 讨论(0)
  • 2020-12-12 13:39

    I have made this generic extension that I use.

    public static class ObjectExtensions {
        public static void With<T>(this T value, Action<T> todo) {
            if (value != null) todo(value);
        }
    }
    

    Then I use it like below.

    string myString = null;
    myString.With((value) => Console.WriteLine(value)); // writes nothing
    myString = "my value";
    myString.With((value) => Console.WriteLine(value)); // Writes `my value`
    
    0 讨论(0)
提交回复
热议问题