The "WhenNull" extension to check for a null value and initialize the base object via lambda

I was asked what was wrong / how the following scenario could be fixed

Customer customer = null;
customer.WhenNull(c => new Customer())
        .Foo();

// instead of
Customer customer = null;
if (customer == null)
{
   customer = new Customer();
}
customer.Foo();

One developer sends me his version of the InNull extension

public static T WhenNull<T>(this T source, Action<T> nullAction)
{
   if (source != null)
   {
      return source;
   } 

   if (nullAction == null)
   {
       throw new ArgumentNullException("nullAction");
   }

   nullAction(source);

   return source;
}

His problem / intention is that he does not want to specify the base object in the lambda expression (in this case, “client”)

Customer customer = null;
customer.WhenNull(c => customer = new Customer())
        .Foo();

I thought this could not be done.
Is it correct?

+3
source share
3 answers

You can do:

static T WhenNull<T>(this T t) where T : class, new()
{
  return t ?? new T();
}

Also noted: you want to use Func<T>not Action<T>as per your code example.

Edit 2:

You probably want:

static T WhenNull<T>(this T t, Func<T> init) where T : class
{
  if (t == null)
  {
    t = init();  // could return here, but for debugging this is easier
  }
  return t;
}

Using:

something.WhenNull(() => new Something()).Foo()
+7

, :

(customer = customer ?? new Customer()).Foo();

.

+2

Instead, you can use Func <T>:

public static T WhenNull<T>(this T source, Func<T> nullFunc)
{
   if (source != null)
   {
      return source;
   } 

   if (nullFunc == null)
   {
       throw new ArgumentNullException("nullFunc");
   }

   return nullFunc();
}

Or, since leppie states use the coalescing operator and the new () if you don't want to specify lamba.

0
source

Source: https://habr.com/ru/post/1766942/


All Articles