c# – How to automatically create a default constructor which sets default values


If you have a class with 20 properties, why do you need a constructor with 20 parameters? Maybe have a sense, but I usually create constructors to initialize properties that are relevant, to simplify the code, not to set all properties.

For your class, you can set the default values when you define the property and all constructors will use this values as the default.

public class User
{
    public int Id { get; set; } = 0;
    public string Name { get; set; } = string.Empty;

    // Here you can even omit the constructor
    public User()
    {
    }
}

Another thing that maybe useful is define a constructor with X parameters and reuse this constructor in other constructors with less parameters:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }

    public User()
        : this(0, string.Empty)
    {
    }

    public User(int id, string name)
    {
        Id = id;
        Name = name;
    }
}

You can replace this(0, string.Empty) for this(default, default) if you want use the default value of each type.



Source link

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top