C # avoid repetition when working with basic constructors

Having two classes: NodeBase and ContentSectionNode that inherit from the abstract NodeBase class, I would like to know if there is a way to avoid repeating the code block in the ContentSectionNode constructors, as well as delegating to the base class constructors.

The abstract classes of the NodeBase class are as follows:

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 outlines of the ContentSectionNode class are as follows:

 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 would like to know if there is a way to avoid recurrence

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

block in all classes of the ContentSectionNode class. Please, not that the _createdBy, _createdAt and UpdateBy, updatedAt fields are accessible only from the ContentSectionNode class and can only be set there.

The project uses C # 5.0, so there are no auto-property initializers. Thanks!

+5
source share
1 answer

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; } 
+7
source

All Articles