Inheritance in C #

What is the difference between

class abc : qwe { } 

and

 class zxc : qwe { zxc() : base(new someAnotherclass()). { } } 
+4
source share
6 answers

The difference is that in the first code fragment you call the constructor of the dimensionless base class, while in the second code fragment you call the constructor of the base class with the parameter.

Your base class can be defined as follows:

 class qwe{ public qwe(){ /* Some code */ } public qwe(SomeAnotherclass ac){ /* Some other code */ } } 

The default constructor for your abc class looks something like this:

 class abc{ public abc() : base() {} } 
+10
source

The first class, whose base is qwe . The second is the same, but it also has a constructor that executes the specified constructor (with different arguments, and then one by default) from the base class when called.

The second fragment shows how to handle the situation when the base class does not have a default constructor. The reason for this requirement is that the constructor of the derived class always invokes the constructor of the base class. If the base constructor needs some parameters, then you should name it explicitly.

0
source

When it comes to inheritance, they are both the same: zxc is_a qwe

In your second example, you simply define an empty zxc constructor to call the qwe constructor earlier with the argument you generate (someAnotherclass ()). This usually means aggregation if you store the link somewhere rather than inheritance.

0
source

The result will be the same.

By invoking the constructor on zxc, you can add some functionality and invoke the base constructor.

0
source

In the second code snippet, you are chaining the default constructor (without parameters) of the class inherited to the base constructor that takes someAnotherClass parameter.

When initializing the zxc class, this will invoke the qwe constructor with the new someAnotherClass .

With the first code fragment, nothing from this constructor chain happens.

0
source

Perhaps you mean

 class abc : qwe { } 

and

 class zxc : qwe { public zxc() : base(new someAnotherClass()). { } } 

It means that

 class qwe { // public constructor accepting SomeAnotherType public qwe(SomeAnotherType someAnotherClass) { } } 

This approach is called a nested constructor call or constructor chaining

0
source

All Articles