Solved the problem of inheritance on: http://skills.itvdn.com/

Specifically, the condition is:

After declaring the Base class, create a Derived class inherited from Base so that its field1 defaults to “derived.f1” and field2 to the value “base.f2”.

It would seem nothing complicated, just added the constructor and assigned the necessary values ​​in the fields.

using System; namespace Less03_task01 { class Program { static void Main( string[] args ) { Derived inst = new Derived(); Console.WriteLine("f1 = {0}\tf2 = {1}", inst.field1, inst.field2); Console.ReadKey(); } } class Base { public string field1 = "base.f1"; public string field2 = "base.f2"; } class Derived : Base { public Derived() { field1 = "derived.f1"; field2 = "base.f2"; } } } 

But *** that there, the problem is not solved correctly. Climbed into the tips there it was written:

"Or you can override the field1 with a new field with the same name (use the keyword new)."

What does this mean and how to use it in solving the problem?

  • It seems, and without overlapping the task seems to be solved correctly. Another thing is that most likely it was not accepted due to the fact that you, in the heir, perform assignment to field2. - iluxa1810

1 answer 1

 class Base { public string field1 = "base.f1"; public string field2 = "base.f2"; } class Derived : Base { public new string field1 = "derived.f1"; } 

The term “overlap” means that a derived member will have the same member as the base class and overlap it. In other words, in the derived class there will be a new member that is not related to the base class (as opposed to virtual ones) with the same name.

 var d1 = new Derived(); var d2 = (Base) new Derived(); Console.WriteLine(d1.field1); // derived.f1 Console.WriteLine(d2.field1); // base.f1 

You can override the members of the base class without the new operator, but in this case, the compiler will throw out a warning. In other words, the new operator simply turns off the compiler warning.

  • Oh, thank you very much - Andrei Abiyev