Access to the subclass of the "property from the base class" constructor

I found something strange that I did not expect to work, actually works. I can access the property of the subclass (constant) from the constructor of the base class:

public abstract class Parent { public Parent() { var constName = ConstName; // <-- surprisingly, this works var randomName = RandomName; // <-- surprisingly, this works } public abstract string ConstName { get; } public abstract string RandomName { get; } } public class Child : Parent { public override string ConstName { get { return "Mike"; } } public override string RandomName { get { return new Random().Next().ToString(); } } } 

Name is a non-static property, not a field. I always thought that type initializers (for static and const fields) were executed, and then their base class, and then the base ctor, and then a subclass of ctor. This means that the child is not yet fully constructed, but in the parent ctor.

Is this a β€œlegal” C # that will work under any circumstances? Why does it work?

EDIT:

No, this is not a deceiving question. There is no class scheme in my question.

+5
source share
2 answers

You can access abstract / virtual subtype members. In the end, property recipients are methods.

But.

As you said, the helper class constructor has not yet been executed. Therefore, it can have side effects. This is why you get a warning from FxCop.

 public abstract class Parent { public Parent() { // NullReferenceException here: var nameLength = Name.Length; } public abstract string Name { get; } } public class Child : Parent { private string name; public Child() { name = "My Name"; } public override string Name { get { return name; } } } 

Worse:

 public class Child : Parent { private string name; public Child() { name = "My Name"; } public override string Name { get { // NullReferenceException here. // You didn't expect that this code is executed before // the constructor was, did you? return name.Substring(0, name.Length - 1); } } } 

Therefore, this is not recommended.

+3
source

The parent has the abstract property Parent.Name. Because of the abstract word, you promise that the parent instances (subclasses) will implement the Name property. if they do not, you cannot create its object.

Please note that I say: instances cannot be created. If a subclass does not implement the Name property, the class may exist, but you cannot create it.

The Parent class does not implement the property name, so you cannot create an instance of Parent.

The Child class, however, implements Name, so you can create it, and because you promised that every object (= instance) of the Parent class has a property name, you can be sure that although all you know is its parent , you also know that he has a name.

This is the basic principle of polymorphism in subtyping Wikipedia on polymorphism

This may be the main reason you want to subclass.

+4
source

Source: https://habr.com/ru/post/1232505/


All Articles