Peter
Peter

Reputation: 51

How to avoid duplicating code with multiple constructors?

I need help with multiple class constructors. I do not want to repeat my code, but how?

    public EventModel(string name, DateTime startTime, DateTime endTime)
        : base(name)
    {
        StartTime = startTime;
        EndTime = endTime;
    }

    public EventModel(Guid id, string name, DateTime startTime, DateTime endTime)
        : base(id, name)
    {
        StartTime = startTime;
        EndTime = endTime;
    }

I am looking something like this:

    public EventModel(Guid id, string name, DateTime startTime, DateTime endTime)
        : this(name, startTime, endTime), base(id, name)
    {
    }

Upvotes: 4

Views: 882

Answers (4)

user1181954
user1181954

Reputation: 1

Provide default values for the constructor.

    public EventModel(Guid id = default(Guid), string name = "Default", DateTime startTime = new DateTime(0), DateTime endTime = new DateTime(0))
    : base(id, name)
{
    StartTime = startTime;
    EndTime = endTime;
}

Upvotes: 0

Faisal Shah
Faisal Shah

Reputation: 39

have the base class be implemented like this. Below is just an example

base class

public Text(): this(0, 0, null) {}
public Text(int x, int y): this(x, y, null) {}
public Text(int x, int y, string s) {
  // Actual constructor implementation

Sample use

Text t1 = new Text();               // Same as Text(0, 0, null)
Text t2 = new Text(5, 10);            // Same as Text(5, 10, null)
Text t3 = new Text(5, 20, "Hello");

Upvotes: 0

ErikE
ErikE

Reputation: 50231

If you can modify the base class to accept a nullable Guid, you can make the id parameter optional:

public EventModel(
   string name,
   DateTime startTime,
   DateTime endTime,
   Guid? id = null)
    : base(name, id)
{
   StartTime = startTime;
   EndTime = endTime;
}

Then in your base class, treat a null id the same as the constructor that takes only a name. It's possible doing this would prevent you from avoiding repetition in your base class, but at the same time you might be able to reduce repetition in your base class.

Also, I strongly suggest that you call your Guid type parameter guid. There is almost no benefit from shortening to id, and it is much more likely to confuse and slow down those looking at the code later.

Upvotes: 0

Scott Chamberlain
Scott Chamberlain

Reputation: 127563

Often in situations like this I will refactor the code to a common method, the drawback with this is you can not set readonly fields.

public EventModel(string name, DateTime startTime, DateTime endTime)
    : base(name)
{
    Initialize(startTime, endTime);
}

public EventModel(Guid id, string name, DateTime startTime, DateTime endTime)
    : base(id, name)
{
    Initialize(startTime, endTime);
}

private void Initialize(DateTime startTime, DateTime endTime)
{
    StartTime = startTime;
    EndTime = endTime;
}

Upvotes: 5

Related Questions