This post is about passing parameters to the base class constructor. Suppose our base class (that we are inheriting from) is part of a framework, perhaps Entity Framework. We are required to create a class that inherits from a base class in the framework that has a constructor that requires an argument. So, we set up a class and inherit from the base class. We want to pass our incoming parameter to the base class because that is where the framework’s code operates on that parameter. We have no need of doing anything with that incoming parameter ourselves.
Below is some example code that shows us how we can pass our incoming parameter to the base class. The base class is A. This is in a simple illustration of a console app that I’ve tested. It’s called BaseKeyword. This example code is based on a n article called Base Class Example at Dot Net Pearls.
Below is the slightly modified code from that website.
namespace BaseKeyword { using System; public class A // This is the base class. { public A(int value) { Console.WriteLine("Base constructor A()"); // Executes code in constructor. } } public class B : A // This class derives from the previous class A. { public B(int value) : base(value) { // The base constructor is called first. Console.WriteLine("Derived constructor B()"); // ... Then this code is executed. } } class Program { static void Main() { // Create a new instance of class A, which is the base class. // ... Then create an instance of B. // ... B executes the base constructor. A a = new A(0); B b = new B(1); } } public class C { // if C inherits from A, and we put C : A here, we then get an error that says // There is no argument given that corresponds to the required formal // parameter 'value' of 'A.A(int)'. This will not compile! } }
Here is the output.
Base constructor A() Base constructor A() Derived constructor B() Press any key to continue . . .
DbContext in EF
We use this example of passing a parameter to the base class when we are creating a database context class in Entity Framework. Here is some code from a project I wrote called GeorgrphyReference. The idea here is to create a ASP.NET Core 2 project using the Identity Framework template, and to create two tables that are not an extension of Users, but simply exist on their own, much like a Product or Inventory of products would exist outside of the Users (Customers) themselves.
The DbContext class is the “A” class from the above example. AppDbContext is the “B” class. Our constructor needs to pass options to the base class, DbContext. Our constructor does nothing else, as you can see from the two braces: { }.
using Microsoft.EntityFrameworkCore; using GeographyReference.Models.ReferenceViewModels; namespace GeographyReference.Data { public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } public DbSet<Country> Countries { get; set; } public DbSet<Province> Provinces { get; set; } } }