Why we should create default constructor

I am new to C# and I’m following a course instructions, and created a custom constructor to validate the data.

But I’m wondering: why should we create a default constructor for our class?

This is my code :

public class UserNotification
{
    [Key]
    [Column(Order =1)]
    public string UserId { get; set; }

    [Column(Order = 2)]
    [Key]
    public int NotificationId { get; set; }

    public ApplicationUser User { get; set; }

    public Notification Notification { get; set; }

    public bool IsRead { get; set; }

    protected UserNotification(){ }

    public UserNotification(ApplicationUser user, Notification notification)
    {
        if (user == null)
        {
            throw new ArgumentNullException("user");
        }

        if (notification == null)
        {
            throw new ArgumentNullException("notification");
        }

        Notification = notification;
        User = user;
    }
}

Answer

why should we create a default constructor for our class?

There is no general rule, that you have to create a default constructor. But if you use entity framework, you need an empty constructor because entity framework needs it.

In general, the ecosystem moves away from empty default constructors. Reasons are non nullable properties and immutable data structures, but again – as of today entity framework does not support this.

Leave a Reply

Your email address will not be published. Required fields are marked *