0

I have the following example:

public class CatalogContext : DbContext
{
    public CatalogContext(DbContextOptions<CatalogContext> options) : base(options)
    {

    }
}

I know that public class CatalogContext : DbContext means that CatalogContext inherits DbContext.

But in the next line I only understand that public CatalogContext is a constructor:

public CatalogContext(DbContextOptions<CatalogContext> options) : base(options)

I don't understand what : base(options) is used for, where does it come from or what it's called.

I've been trying to find some info on this, but I don't know what to search for.
I found this list of operators in C#: https://www.tutorialspoint.com/csharp/csharp_operators.htm, but : is found only in the Conditional Expression ? : .
Then I thought, what if it's not an operator. What is it then ?

bleah1
  • 471
  • 3
  • 18
  • 2
    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/base – Matthew Watson May 19 '21 at 11:15
  • 1
    I imagine there's a good duplicate question that I'm just not finding at the moment, but the term you're looking for is "constructor chaining". – David May 19 '21 at 11:17
  • 2
    Does this answer your question? [Passing parameters to the base class constructor](https://stackoverflow.com/questions/23481456/passing-parameters-to-the-base-class-constructor) – Indrit Kello May 19 '21 at 11:20

2 Answers2

4

:base is used to pass the arguments to the constructor of base class from the constructor of child class.

A brief explanation here https://www.delftstack.com/howto/csharp/csharp-call-base-constructor/

A duplicate of Passing parameters to the base class constructor

Indrit Kello
  • 1,293
  • 8
  • 19
3

If a default (parameterless) constructor does not exist on the base class, then in your derived class you must specify the arguments that get passed to the base constructor.

This is done as in your example above:

public class Base
{
  public Base(int x) {...}
}

public class Derived : Base
{
  public Derived(int x, int y) : base(x) {...}
}

Read more here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/base

Chris Pickford
  • 8,642
  • 5
  • 42
  • 73