2

I'm just trying to understand how Inheritance works in C#. (even though I think I got it, I want to try to do something practical in order to understand)

So I've been trying to create a class with a property and a constructor and another one which inherits this one. But I get an error and I don't really seem to get why.

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApp2
{
    public class Test
    {
        public int testing { get; }
        public Test(int p)
        {
            this.testing = p;
        }
    }
    public class Test2 : Test {

    }
}
There is no argument given that corresponds to the required formal parameter 'p' of 'Test.Test(int)' for line 15

Can someone help me understand what's happening and why do I get that error? Thanks.

1 Answers1

7

TL;DR: Constructors aren't inherited.

Longer explanation: Your Test2 class implicitly has a constructor like this:

public Test2() : base()
{
}

... because you haven't declared any constructors in Test2. If you declare any constructor in Test2, the compiler won't try to provide the implicit one. (Your constructor will need to call base(...) providing a value for p though.

So you probably want:

public class Test2 : Test
{
    public Test2(int p) : base(p)
    {
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I have 2 questions, if you don't mind, because those are pretty silly questions (I'm really a noob): why do I need a constructor (can't the class just exist? is it mandatory to have a constructor?) and how does base() work (what's its role?)? – Octavian Niculescu May 05 '20 at 18:57
  • @JohnSmith: Yes, there has to have a constructor unless it's a static class (in which case it can't inherit from anything). There's no point in inheriting if you can't create an instance. As for the purpose of `base` - see https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/base. (It's really not something that can be explained in a comment.) – Jon Skeet May 05 '20 at 19:00
  • Thanks a lot. I really appreciate your effort. I will accept your answer asap. – Octavian Niculescu May 05 '20 at 19:01
  • Hey I'm still looking into this example and I can't really understand what's happening. What is base(p) calling? I've been looking on that page but I can't still figure it out. is base(p) calling the constructor of Test? – Octavian Niculescu May 06 '20 at 17:16
  • @JohnSmith: It's chaining to the constructor in the base class. It's the second bullet at the top: "Specify which base-class constructor should be called when creating instances of the derived class." – Jon Skeet May 06 '20 at 17:58