Implementing interfaces with auto-implemented properties in C#

I know that you hate when you are implementing an interface with a bunch of properties, you use the Crtl + . and hit Implement interface and you get getter and setter with the NotImplementedException();

Let’s see what I’m talking about, you have the following interface:

public interface IAuditable
{
    DateTime CreatedDate { get; set; }
    String CreatedBy { get; set; }
    DateTime UpdatedDate { get; set; }
    String UpdatedBy { get; set; }
}

Now, you want to implement the interface in a class. With help of Visual Studio you use Ctrl + . click Implement interface and this is what you get:

public class MyEntity: IAuditable
{
    public DateTime CreatedDate { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
    public string CreatedBy { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
    public DateTime UpdatedDate { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
    public string UpdatedBy { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
}

But, how can we change this default behavior? Well, in Visual Studio 2019 you can go through Tools > Options… > Text Editor > C# > Advance and in the group Implement Interface or Abstract Class select When generating properties: prefer auto properties

Show Visual Studio 2019 Options to configure auto properties when you are implementing an interface

The next time that implement the same interface this is what you will get:

public class MyEntity: IAuditable
{
    public DateTime CreatedDate { get; set; }
    public string CreatedBy { get; set; }
    public DateTime UpdatedDate { get; set; }
    public string UpdatedBy { get; set; }
}

This can help you save time because almost all the time you need auto-implmented properties.

Leave a Reply