4.5: Adding Extension Method

Our DTOs are returning an Age property instead of a DateOfBirth property.

Unfortunately, DateTime does not have a method to calculate age from a given date.

So, we'll have to add our own method on the DateTime class to do it for us!

Add Helpers Project

Navigate to the root of your project in your command line and run the following to create a new project called Helpers:

dotnet new classlib -o EFConnect.Helpers --framework netcoreapp2

Create Extensions Class

Inside of the new .Helpers project, add a new static class called Extensions.cs

Inside of this class, we'll add a static method that calculates the age based on the DateOfBirth:

public static class Extensions
{
    public static int CalculateAge(this DateTime dateTime)
    {
        var age = DateTime.Today.Year - dateTime.Year;
        if (dateTime.AddYears(age) > DateTime.Today)
        {
            age --;
        }

        return age;
    }
}

Adding a Project Reference

Next, we need to add a project reference in the .Services project to the .Helpers project.

In your EFConnect.Services.csproj file add a new reference to the .Helpers project:

<ItemGroup>
    <ProjectReference Include="..\EFConnect.Data\EFConnect.Data.csproj" />
    <ProjectReference Include="..\EFConnect.Models\EFConnect.Models.csproj" />
    <ProjectReference Include="..\EFConnect.Contracts\EFConnect.Contracts.csproj" />
    <ProjectReference Include="..\EFConnect.Helpers\EFConnect.Helpers.csproj" />            //  <--- Added
</ItemGroup>

Last updated