1

I have these two lines of code:

result.birthdateSpecified = (someData.BirthDate != null || false);
result.birthdate = someData.BirthDate as DateTime;

I'd like to be able to set the result.birthdate to the someDate.BirthDate, only if it exists, in a single line. So that I don't have to write any if statement. Just wondering if it's possible?

FYI - result.birthDate is a DateTime and someData.BirthDate is a DateTime? (nullable)

I know I can't cast it with 'as' but not sure if there is something else I can use?

chuckd
  • 13,460
  • 29
  • 152
  • 331

4 Answers4

4

what about the null coalescing operator?

result.birthdate = someData.BirthDate ?? result.birthdate;

sure, the assignment will be done unconditionally, so the setter will be called, and the getter might be called... which might be a thing you don't want ... but the value will only change if someData.BirthDate is not null

DarkSquirrel42
  • 10,167
  • 3
  • 20
  • 31
3

In addition to the other answers you can edit the first line as well to use the HasValue property of Nullable types:

result.birthdateSpecified = someData.BirthDate.HasValue;
result.birthdate = someData.BirthDate ?? default(DateTime);
Simply Ged
  • 8,250
  • 11
  • 32
  • 40
2

I would do:

result.birthdate = someData.BirthDate ?? default(DateTime);

Or you could replace default(DateTime) with whatever sentinel value you're using when birthdateSpecified is false.

I think it makes more sense from a client POV to ensure that when birthdateSpecified is false, there is a predictable "dummy" value in the birthdate field, rather than potentially leaving correct-looking data there.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
1

You could do a combination of a null coalesce and self assignment:

result.birthdate = someData.BirthDate ?? result.birthdate;
devNull
  • 3,849
  • 1
  • 16
  • 16