0

I had to do a code review for one of the business applications written in core C#. The framework includes entities and I see this pattern in all entity classes where an overloaded constructor takes the entity as a parameter. A simplified version of it looks like -

public class SomeEntity
{
    public SomeEntity()
    {
        this.Name = string.Empty;
    }

    public SomeEntity(SomeEntity entity)
    {
        if (entity == null)
        {
            throw new System.ArgumentNullException("entity");
        }
        this.Name = entity.Name;
    }
    public string Name { get; set; }
}

Not sure if a code generator or template was used, but this is common across all entities and wondering if there is a pattern around it. I have never come across this kind of code and wondering if it makes sense.

Why would the same entity be a parameter of an overloaded constructor and how can this be used at all as the entity has to be created before it can be passed to the overload?

Lalman
  • 946
  • 2
  • 11
  • 27
  • http://stackoverflow.com/questions/12051/calling-base-constructor-in-c-sharp?rq=1 – Philip Gullick Dec 10 '13 at 12:41
  • 1
    That's a copy constructor and allows for cloning of like objects. Usually the constructor would be setting more values than just one as in your example.. http://msdn.microsoft.com/en-us/library/ms173116.aspx – Dave Lawrence Dec 10 '13 at 12:41

1 Answers1

2

That's a copy constructor and allows for cloning of like objects. Usually the constructor would be setting more values than just one as in your example..

See here http://msdn.microsoft.com/en-us/library/ms173116.aspx

Dave Lawrence
  • 3,843
  • 2
  • 21
  • 35
  • Gotcha, makes sense and I could recollect what a copy constructor means...thanks for quick reply....A quick addition - Is it a generic pattern (irrespective of whether it is actually used) that goes by default for entity kind of objects? – Lalman Dec 10 '13 at 12:49
  • Soom tools/organisations might consider it a default/generic pattern but it would all depend on the motivation for using it. I've only ever required a handful of copy constructors but it's a handy pattern to remember – Dave Lawrence Dec 10 '13 at 12:55