What is wrong with accessing virtual members in a constructor in C #?

Source: Internet
Author: User

If a virtual property or virtual method is defined in a class, and the virtual property or method is accessed in the constructor, VisualStudio does not give a warning and compiles without problems, but if the ReSharper plugin is installed, a warning is given: "Virtual members are accessed in the constructor ", then, why is this a security risk, and here's an example to illustrate:

using System;namespace virtualdemo{class Program {static void Main (string[] args)            {var test = new Subclass ();        Console.readkey ();        }} class BaseClass {Protected virtual string Virtualproperty {get; set;}            Public BaseClass () {var p = virtualproperty;        Virtualmethod (); } protected virtual void Virtualmethod () {}} class Subclass:baseclass {private M        Ockclass _mockclass;        Public subclass () {_mockclass = new Mockclass ();            } protected override string Virtualproperty {get {return _mockclass.mockproperty;}        set {_mockclass.mockproperty = value;}        } protected override void Virtualmethod () {var p = _mockclass.mockproperty;    }} class Mockclass {public string Mockproperty {get; set;} }}

The example is simple because a null reference error occurred while constructing subclass because the base class constructor was run before the subclass constructor, and a member class was initialized in the subclass constructor, but the subclass was not constructed when the base class constructor accessed the virtual member. So there was a null citation error. There are several ways to avoid this, you can construct the member class by the way the subclass field is initialized, this syntax sugar avoids the constructor's timing problem, and the second is a virtual initialize method that can be defined in the first step of the subclass constructor, where the subclass initializes the required dependency when inheriting the method.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.