alex.g
alex.g

Reputation: 187

C# avoid repetition when working with base constructors

Having two classes, NodeBase and ContentSectionNode which inherits from the abstract class NodeBase, I'd like to know if there is any way to avoid repeating a block of code in the ContentSectionNode constructors, while also delegating to the base class constructors.

The abstract NodeBase class ctors look like this:

protected NodeBase(string tagType, string content)
  : this()
{
  TagType = tagType;
  Content = content;
}

protected NodeBase(Guid? parentId, int? internalParentId, string tagType, string content) 
  : this(tagType, content)
{
  ParentId = parentId;
  InternalParentId = internalParentId;
}

The ContentSectionNode class ctors look like these:

public ContentSectionNode(Guid createdBy)
  : this()
{
  _createdBy = createdBy;
  _createdAt = DateTime.Now;
  UpdatedAt = _createdAt;
  UpdatedBy = _createdBy;
}

public ContentSectionNode(Guid createdBy, string tagType, string content)
  :base(tagType, content)
{
  _createdBy = createdBy;
  _createdAt = DateTime.Now;
  UpdatedAt = _createdAt;
  UpdatedBy = _createdBy;
}

public ContentSectionNode(Guid createdBy, Guid? parentId, int? internalParentId, string tagType, string content)
  : base(parentId, internalParentId, tagType, content)
{
  _createdBy = createdBy;
  _createdAt = DateTime.Now;
  UpdatedAt = _createdAt;
  UpdatedBy = _createdBy;
}

I'd like to know if there is any way that I can avoid repeating the

_createdBy = createdBy;
_createdAt = DateTime.Now;
UpdatedAt = _createdAt;
UpdatedBy = _createdBy;

block in all the ctors of the ContentSectionNode class. Please not that the _createdBy, _createdAt and UpdatedBy, UpdatedAt fields/props are only accessible from the ContentSectionNode class and can only be set there.

The project is using C# 5.0, so no auto-property initializers. Thanks!

Upvotes: 5

Views: 250

Answers (1)

Bob Brinks
Bob Brinks

Reputation: 1392

Like this?

public ContentSectionNode(Guid createdBy)
  : this(createdBy,null,null, null, null)
{
}

public ContentSectionNode(Guid createdBy, string tagType, string content)
  : this(createdBy, null, null tagType, contect)
{
}

public ContentSectionNode(Guid createdBy, Guid? parentId, int? internalParentId, string tagType, string content)
  : base(parentId, internalParentId, tagType, content)
{
  _createdBy = createdBy;
  _createdAt = DateTime.Now;
  UpdatedAt = _createdAt;
  UpdatedBy = _createdBy;
}

Upvotes: 7

Related Questions