Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 428
alex.g Avatar asked Aug 31 '16 11:08

alex.g


1 Answers

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;
}
like image 90
Bob Brinks Avatar answered Sep 19 '22 08:09

Bob Brinks