Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# base() constructor order [duplicate]

Possible Duplicate:
C# constructor execution order

class Foo {     public int abc;     Foo()     {        abc = 3;     }  }  class Bar : Foo {     Bar() : base()     {        abc = 2;     } } 

In the example above, when an object of Bar is created, what will be the value of BarObject.abc? Is the base constructor called first, or is Bar() run, /then/ the base() constructor?

like image 867
Xenoprimate Avatar asked Jan 07 '10 15:01

Xenoprimate


2 Answers

It'll be 2. Constructors run in order from base class first to inherited class last.

Note that initialisers (both static and instance variables) run in the opposite direction.

The full sequence is here: http://www.csharp411.com/c-object-initialization/

like image 180
Paolo Avatar answered Oct 22 '22 21:10

Paolo


First base class constructor is called followed by the derived class constructor. The result is 2. You should explicitly state the accessibility of that class variable. Is it protected, private or public?

I see you changed it to public now, so it will be 2.

This link will further help you understand constructors, how they are used, when they are called, and order of constructor call when you use inheritance:

http://www.yoda.arachsys.com/csharp/constructors.html

Also you may want to actually try this out yourself, you will learn more by practicing and writing code then just reading it.

Try to declare Bar and output its value. Use some properties:

 class Foo     {         public int abc;         public Foo()         {             abc = 3;         }          public int ABC         {             get { return abc; }             set { abc = value; }         }      }      class Bar : Foo     {         public Bar() : base()         {             abc = 2;         }     }        class Program     {         static void Main(string[] args)         {             Bar b = new Bar();             Console.WriteLine(b.ABC);             Console.ReadLine();          }     } 

A simple printout would yield the result you are looking for. Here is the output:

alt text

Don't you just love my namespace :-). By the way you could also use automatic properties so that the property is simply public int ABC {get;set;}.

like image 35
JonH Avatar answered Oct 22 '22 23:10

JonH