IAuditable Interface - .NET Framework

Implementation

When creating a new instance of an entity.

var i = new Invoice();
i.Created(user);

When updating an existing entity

i.Modified(user);

Applying to a database entity.

public partial class Invoice : IAuditable { }

Reusable Code

public interface IAuditable
{
    DateTime UpdatedOn { get; set; }
    string UpdatedBy { get; set; }
    DateTime CreatedOn { get; set; }
    string CreatedBy { get; set; }
}


public static class IAuditableExtension
{
    public static void Audit(this IAuditable e, bool createNew, string byUser)
    {
        if (e == null)
            return;

        var dtNow = DateTime.UtcNow;

        if (createNew)
        {
            e.CreatedOn = dtNow;
            e.CreatedBy = byUser;
        }

        e.UpdatedOn = DateTime.UtcNow;
        e.UpdatedBy = byUser;
    }

}

Future Improvements

An improvement that can be made is that the Audit method automatically "know" if the entity is new or existing. See this article or this one for ideas how to do this.