Get the value of and with using the null-coalescing operator

Posted by Jonas Elfström Fri, 15 May 2009 22:38:00 GMT

I like the ?? operator that surfaced in C# 2.0. I'm often in environments where null values florish and ?? is a great way to handle them, especially for presentation. A while ago I found a use for the ?? operator in a way I'd never used it before.

The problem at hand was to return an account number from data that could be described as somewhat inconsistent.

The application had left room for the users to enter accounts in two by two ways. A customer could have multiple subsidiaries and in each subsidiary, by misconception, two different fields had been used as the account number. It was also possible to connect an account to all subsidairies of a customer at the same time as a specific subsidiary of that customer had an account defined.

Only if a unique account could be found it should be returned. All other cases should return a cause of failure so that the users could use that information to clean up the mess.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
private static Account GetCustomerAccount(Customer customer)
{
  bool hasAccount = !String.IsNullOrEmpty(customer.AccountNo);
  bool hasAccountNoExtra = !String.IsNullOrEmpty(customer.AccountNoExtra);
  bool hasAllSubsAccount = !String.IsNullOrEmpty(customer.AccountNoAllSubs);
  bool hasAllSubsAccountNoExtra = 
       !String.IsNullOrEmpty(customer.AccountNoExtraAllSubs);
  var account = new Account();

  if ((hasAccount || hasAccountNoExtra) &&
      (hasAllSubsAccount || hasAllSubsAccountNoExtra)) 
  {
    account.Status = account.HasBothAllSubsAndSpecific;
    return account;
  }
  if ((hasAccount && hasAccountNoExtra) ||   
      (hasAllSubsAccount && hasAllSubsAccountNoExtra)) 
  {
    account.Status = account.HasBothAccountAndAccountExtra;
    return account;
  }

  account.AccountNo = customer.AccountNo ??
                      customer.AccountNoExtra ??
                      customer.AccountNoAllSubs ??
                      customer.AccountNoExtraAllSubs;

  if (account.AccountNo==null)
    account.Status=account.HasNoAccountDefined;

  return account;
}


Notice how AccountNo is set to the first non null value of the four. Imagine that with plain ifs. Here I believe the ??-operator both makes the code clear and saves us from a bunch of nested ifs.

Posted in C# | no comments

Comments

Comments are closed