How to calculate age in C#

Seems like a simple thing, but the fact that you need to subtract a year if the person hasn’t had their birthday yet in the current year made it more involved. There were a lot of different ways to do it online, some of them more clunky than others. I cobbled this together from the various posts I found (assume a Person object with a DOB field).

public int Age {

  • get {
    • var now = DateTime.Now;
    • var age = now.Year - this.DOB.Year;
    • return (this.DOB.DayOfYear <= now.DayOfYear) ? age : age - 1;
  • }

}

Advertisements

Unique constraint that allows multiple nulls and empty strings

T-SQL’s UNIQUE constraint allows for NULL values, but only one null value is allowed per column. There is, however, a nifty little way around this, via the WHERE clause.

For example, here’s a UNIQUE constraint that makes sure an ID is unique but allows for both multiple NULL values and multiple empty strings:

CREATE UNIQUE NONCLUSTERED INDEX [UNIQUE_ID] ON [dbo].[tblParticipant]
(
[ID] ASC
)
WHERE ([ID] IS NOT NULL AND [ID] <> ”)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO