简体   繁体   中英

basic constructor question regarding objects in c#

Hey guys, just starting out with C#. I had a few doubts, would really appreciate it if anyone could help me out here.


Question 1

   namespace borrowmoney
    {
        public partial class Form1 : Form
        {
            guy nikhil = new guy();

             public Form1()
            {
                InitializeComponent();


                nikhil.cash=50;
             }
          }
    }

here in the above program form1() constructor should run first but the instantiation is done outside the constructor so how would the constructor come to know about the instantiation and in return use guy's data members(cash is a data member of of guy class ) ?

When the code is compiled, the instantiation will be moved to the constructor. It will be instantiated before the body of your constructor is executed.

@Mehrdad's handled the ordering issue. I think, though, with respect to your second question that you need to read up on scoping and accessibility rules. The order of evaluation is related to the scope, in the sense that there are rules that define the order of evaluation based on scope, but the knowledge (accessibility) of a particular member isn't defined by the order of evaluation. In this case because the variable is an instance variable, it can be referenced anywhere in the class including the constructor. If it hadn't been given a value prior to the constructor being run, you would have gotten a null reference exception, but the legality of accessing it's members depends, not on when the value is assigned, but how the variable and it's members are declared with respect to accessibility.

Take a look at Jon Skeets Constructor Page to answer all your constructor and member variable initialization questions. Its a great detailed explanation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM