I am currently working on a ASP.NET Core MVC application (I am migrating a project from .NET to .NET Core) and I was wondering about the base constructors.
Specifically, codes like:
public partial class CompanyFormsContext : DbContext
{
public CompanyFormsContext()
: base("name=CompanyFormsContext")
{
}
public CompanyFormsContext(string connName)
: base("name=" + connName)
{
}
...
}
//First
var db = new CompanyFormsContext(siteUrl.StartsWith("http://www.") ? "CompanyFormsContext" : "CompanyFormsContextQA");
//Second
var env = Request.Headers["environment"].First();
var db = new CompanyFormsContext(env);
A base class constructor is used if there's some kind of initialization that's used in many different scenarios. For example, if you had something like
public bool Abc { get; set; }
private readonly string x;
private readonly string newName;
public Test(string x, string newName)
{
Abc = true;
thix.x = x;
this.newName = newName;
}
(yeah, pretty dumb example, but anyway) and you always wanted that initialization to happen you probably don't want to have to type that over and over again every time you have a new derived class. Not only would that be annoying, it would be bad from a maintenance perspective; if you had to change the logic for some reason you'd have to go to every single place where you had typed it and change it, and if you accidentally missed one you'd introduce a bug into your system.
Note that it's possible for both the parent type and the derived type to have several constructors. For example:
public abstract class SomeClass
{
public SomeClass(string a, string b)
{
// ...
}
public SomeClass()
{
//...
}
}
public SomeDerivedType : SomeClass
{
public SomeDerivedType(string a, string b) : base(a, b)
{
// ...
}
public SomeDerivedType() : base("test", "string")
{
// ..
}
}
It's perfectly valid for the base constructor and derived type constructor to have different parameters. If you think about it, that makes sense; you're calling a completely different constructor. It would, for example, be perfectly valid to do the following:
public SomeDerivedType()...
{
// The CollectionType constructor has a different number of parameters than SomeDerivedType does
abc = new CollectionType<int>(1, 2, 3, 4, 5);
}