C# constructor execution order - c#

In C#, when you do
Class(Type param1, Type param2) : base(param1)
is the constructor of the class executed first, and then the superclass constructor is called or does it call the base constructor first?

The order is:
Member variables are initialized to default values for all classes in the hierarchy
Then starting with the most derived class:
Variable initializers are executed for the most-derived type
Constructor chaining works out which base class constructor is going to be called
The base class is initialized (recurse all of this :)
The constructor bodies in the chain in this class are executed (note that there can be more than one if they're chained with Foo() : this(...) etc
Note that in Java, the base class is initialized before variable initializers are run. If you ever port any code, this is an important difference to know about :)
I have a page with more details if you're interested.

It will call the base constructor first. Also keep in mind that if you don't put the :base(param1) after your constructor, the base's empty constructor will be called.

The constructor of the baseclass is called first.

Not sure if this should be a comment/answer but for those who learn by example this fiddle illustrates the order as well: https://dotnetfiddle.net/kETPKP
using System;
// order is approximately
/*
1) most derived initializers first.
2) most base constructors first (or top-level in constructor-stack first.)
*/
public class Program
{
public static void Main()
{
var d = new D();
}
}
public class A
{
public readonly C ac = new C("A");
public A()
{
Console.WriteLine("A");
}
public A(string x) : this()
{
Console.WriteLine("A got " + x);
}
}
public class B : A
{
public readonly C bc = new C("B");
public B(): base()
{
Console.WriteLine("B");
}
public B(string x): base(x)
{
Console.WriteLine("B got " + x);
}
}
public class D : B
{
public readonly C dc = new C("D");
public D(): this("ha")
{
Console.WriteLine("D");
}
public D(string x) : base(x)
{
Console.WriteLine("D got " + x);
}
}
public class C
{
public C(string caller)
{
Console.WriteLine(caller + "'s C.");
}
}
Result:
D's C.
B's C.
A's C.
A
A got ha
B got ha
D got ha
D

[Edit: in the time it took me to answer, the question had totally changed].
The answer is that it calls the base first.
[Original answer to the old question below]
Are you asking when you would do the "base" bit of the constructor call?
If so, you would "chain" a call to the constructor base if the class is derived from another class which has this constructor:
public class CollisionBase
{
public CollisionBase(Body body, GameObject entity)
{
}
}
public class TerrainCollision : CollisionBase
{
public TerrainCollision(Body body, GameObject entity)
: base(body, entity)
{
}
}
In this example, TerrainCollision derives from CollisionBase. By chaining the constructors in this way, it ensures the specified constructor is called on the base class with the supplied parameters, rather than the default constructor (if there is one on the base)

Your question is a bit unclear but I'm assuming you meant to ask the following
When to I call the base constructor for my XNA object vs. using the impilict default constructor
The answer to this is highly dependent on both your scenario and the underlying object. Could you clarify a bit wit the following
What is the scenario
What is the type of the base object of TerrainCollision?
My best answer though is that in the case where you have parameters that line up with the parameters of the base class`s constructor, you should almost certainly be calling it.

Constructor mechanism is much better as it leaves the application to use constructor chaining and if you were to extend the application it enables through inheritance the ability to make minimal code changes.
Jon Skeets Article

Related

Design pattern for overcoming the reverse constructor order?

I have the following problem:
The base class expects to receive some data but the data is initialized by the derived class constructor which in C# is called after the base constructor was called.
Context / What I'm trying to solve:
Let's call the base class Track, its role is to build a mesh that represents a track for a video game.
The derived classes, e.g. Track1 each fetch track data from a particular file format, with significant differences that forbids implementing the whole code in base class Track.
The main job of Track is to abstract the data incoming from derived classes and for this it has abstract members that derived classes have to implement, e.g. int GetVertexCount, Vector3 GetVertex(int).
Think more of less of it being an IPicture interface that can load from different formats, e.g. BMP, JPEG, and return the whole thing as an abstraction.
The problem I am facing:
In C#, base class constructors are called before derived class constructor, but I must initialize something in the derived class constructor that in turn I must pass to the base class constructor. And while I'm on it, I would like to have members to be immutable, i.e. readonly.
Question:
How can I run some code in derived class constructor first, so I can pass the result to the base constructor ?
Answer:
Following #Kit answer here's how I ended up doing and it's just fine:
Ironically, it ended up being a C-like API :)
Assuming you don't need an instance of your derived class to do the logic you want, you can call a static method from your derived constructor prior to calling the base constructor.
Here is a simplistic example
public class Base
{
protected Base(SomeType data)
{
// base logic using data
}
}
public class DerivedOne : Base
{
public DerivedOne(int some, string data) : base(DerivedLogic(some, data))
{
...
}
private static SomeType DerivedLogic(int some, string data) => ...
}
public class DerivedTwo : Base
{
public DerivedTwo (string moreStuff) : base(DerivedLogic(moreStuff))
{
...
}
private static SomeType DerivedLogic(string moreStuff) => ...
}
This runs in the following order:
Static method DerivedLogic
Base class constructor (using the value from DerivedLogic)
Derived constructor
Now, that's slightly weird. What might be better is the derived logic not be a part of the derived class at all. What do I mean? I mean you have a third class that is passed into the derived constructor, and then on to the base constructor. That gives you the same effect.
public class Base
{
protected Base(SomeOtherType dataWrapper)
{
var data = dataWrapper.DerivedLogic();
// base logic using data
}
}
public class DerivedOne : Base
{
public DerivedOne(SomeOtherType otherType) : base(otherType)
{
...
}
}
Or calculate SomeType somewhere prior to calling any constructors and then pass it in. Either of these ways is a better design because it follows SRP:
Base class responsible for what it does.
Logic for constructing a track has that single responsibility.
Derived class has it's single responsibility.
There's not a really elegant way to do exactly what you're asking for, but I would question whether it's really necessary. It's usually a code smell to see logic in a constructor.
There are lots of other approaches you can take, like using a static Create() method.
class Derived : Base
{
private readonly object _o;
private Derived(object o, string s) : base(s)
{
_o = o;
}
public static Derived Create(string path)
{
var o = new object();// initialize from path
var s = o.ToString(); // get s from o.
return new Derived(o, s)
}
}
You could also consider using composition over inheritance:
class Base
{
private readonly string _s;
public Base(string s)
{
_s = s.ToLower();
}
}
class Derived
{
private readonly object _o;
private readonly Base _b;
public Derived(string path)
{
_o = new object();// initialize from path
_b = new Base(_o.ToString());
}
}
But it's really difficult to know which of these approaches might be appropriate without knowing what your actual goals and constraints are. You've told us how you want to solve your problem, and not what problem you're trying to solve.

Base class object as argument for derived class

(Simplified) Scenario:
public class BaseClass
{
public int BaseClassInt {get; set;}
public BaseClass(int pBaseClassInt)
{ this.BaseClassInt = pBaseClassInt; }
}
public class DerivedClass : BaseClass
{
public int DerivedClassInt {get; set;}
public DerivedClass (int pBaseClassInt, int pDerivedClassInt) : base(pBaseClassInt)
{ this.DerivedClassInt = pDerivedClassInt; }
}
If I want to instantiate a DerivedClass-object I have to pass all arguments required to create a BaseClass-object and a DerivedClass-object. Also for every BaseClass-constructor I have to (at least should in my concrete case) provide a constructor with the same arguments in the derived class, plus arguments for the derived class properties. Then, if I change or delete a constructor in the base class I have to change or delete the corresponding contructor in the derived class(es).
I wonder if it is possible to use a constructor for the derived class which accepts a base class-object as an argument:
public DerivedClass(BaseClass pBaseClassObejct, int pDerivedClassInt)
{
// to make clear what I intend to do - looks silly of course
this = (DerivedClass)pBaseClassObject;
this.DerivedClassInt = pDerivedClassInt;
}
This could be called:
DerivedClass DerivedClassObject = new DerivedClass((new BaseClass(1),2);
If constructors in the base class would change, I wouldn´t have to mind it for the derived class. Is there any way to achieve this?
Think about this line for a moment:
this = (DerivedClass) pBaseClassObject;
Let's ignore the fact that you cant set this directly that way, and focus on the rest.
Imagine Giraffe and Elephant are both implementations of AfricanAnimal:
// By extension, ellie is also an AfricanAnimal
Elephant ellie = new Elephant();
// assume ellie is passed in as a param here (she can
// be, because she is an AfricanAnimal after all!):
public Giraffe(AfricanAnimal ellie)
{
this = (Giraffe) ellie; // Can't do this!
}
You can't (and would not want to) force ellie into being a giraffe, because a giraffe may have properties etc. that ellie lacks, and ellie may have properties that Giraffes don't have. Yet, using an AfricanAnimal as your parameter type there, would allow for just that.
Note: You could write that code and pass a Giraffe in, and all would be fine, but then again, that makes little sense; then you might as well use the Giraffe type as the parameter.
If you replace this with an instance variable, you would be able to compile with something like the following...
public Giraffe(AfricanAnimal ellie)
{
this.varOfTypeGiraffe = (Giraffe) ellie;
}
... but as soon as you run it with an Elephant as a a prameter, you will get an exception similar to:
InvalidCastException: Unable to cast object of type 'Elephant' to type 'Giraffe'.
TL;DR: This is a bad idea. Don't even try.
You cannot make a base constructor run from inside the body of any derived method (including the derived constructor). Even if you could, a base instance would not have retained any information about which constructor was used to instantiate it so there would be no way to know which base constructor should be called.
The above refers to the general case where a base constructor can potentially modify application state not directly related to the base class (e.g. by changing the value of static fields somewhere). You could use reflection to copy property values from a base instance to the derived instance being created, but this is practically unworkable because
It requires that you create a base instance in the first place -- what if the base is abstract, or if creating one has side effects?
You need a guarantee that the base constructor does not modify application state. But the aim here is to be independent of what the base constructors do, so you are back to square one.
No, that is not possible and should not be, because it doesn't make sense.
If it was possible and you deleted/changed the base class constructor, you would still need to change the code which creates the base class object that you would use as an argument to the derived class constructor.
Also, not all base classes are concrete. You would not be able to create an abstract base class, right?
This feature is not available. I think what you want is a little like this:
Suppose C# had a keyword allbaseargs and allowed code like this:
public class DerivedClass : BaseClass
{
public int DerivedClassInt { get; set; }
public DerivedClass (allbaseargs, int pDerivedClassInt)
: base(allbaseargs)
{
DerivedClassInt = pDerivedClassInt;
}
}
Then this could only work if BaseClass had only one (accessible) instance constructor.
The compiler should then examine the sole base constructor and substitute the magical word allbaseargs with the parameters of that constructor.
However, C# does not have this feature, and you would have to hand-code everything, which includes changeing all : base(...) calls of all derived classes when the constructor signature changes.
It is allowed to have the signature:
public DerivedClass(BaseClass pBaseClassObejct, int DerivedClassInt)
like you suggest, but you would not be able to chain the : base(...) easily. You would have to equip BaseClass with a construtor that took another instance in and copied all "state" (all instance properties and fields and such) from that other instance to "this". I do not recommend that solution.
This might be help!
Solution A: Create Inherit instead of base!
public static class Test
{
public static T Foo<T>(string text, int num) where T : BaseClass
{
T #base = (T)Activator.CreateInstance(typeof(T), new object[] { text, num });
//...
return #base;
}
public static void Main()
{
InheritClass inherit = Foo<InheritClass>("Hi there", 10);
}
}
Solution B: Copy base to inherit
public static class Test
{
public static TInherit As<TBase, TInherit>(this TBase #this) where TInherit : TBase
{
var type = typeof(TInherit);
var instance = Activator.CreateInstance(type);
foreach (var property in type.GetProperties())
if (property.CanWrite)
property.SetValue(instance, property.GetValue(#this, null), null);
return (TInherit)instance;
}
public static BaseClass Foo(string text, int num)
{
BaseClass #base = new BaseClass(text, num);
//...
return #base;
}
public static void Main()
{
InheritClass inherit = Foo("Hi there", 10).As<BaseClass, InheritClass>();
}
}
Notes: you can have simple 'As()' found here, but i prefer mine (where Inherit : TBase), where it's more safe and support converting base to inherit of inherit class.

Order of calling constructors case of inheritance in c# [duplicate]

This question already has answers here:
C# constructor execution order
(7 answers)
Closed 5 years ago.
I was just reading Inheritance in C# in which i came across the Constructors and was written that constructors are executed in order of derivation. What does it mean?That base class constructor will be called first or Derived class.
A base class Constructor is called first.Refer to the following example
// Demonstrate when constructors are called.
using System;
// Create a base class.
class A {
public A() {
Console.WriteLine("Constructing A.");
}
}
// Create a class derived from A.
class B : A {
public B() {
Console.WriteLine("Constructing B.");
}
}
// Create a class derived from B.
class C : B {
public C() {
Console.WriteLine("Constructing C.");
}
}
class OrderOfConstruction {
static void Main() {
C c = new C();
}
}
The output from this program is shown here:
Constructing A.
Constructing B.
Constructing C.
The base class constructor will be called first. You can test this pretty easily yourself:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DerivationTest
{
class Program
{
public class Thing
{
public Thing()
{
Console.WriteLine("Thing");
}
}
public class ThingChild : Thing
{
public ThingChild()
{
Console.WriteLine("ThingChild");
}
}
static void Main(string[] args)
{
var tc = new ThingChild();
Console.ReadLine();
}
}
}
Class constructors are called in the order implied by derivation, but it's important to note that in C#, field initializers (e.g. int foo=5) are run before the base class constructor, and thus run in the opposite order. This is primarily useful if the base constructor may cause virtual function which is overridden in the derived class to be called before the base constructor has completed. Such a function will see any variables that were initialized by field initializers as having been initialized.
VB.net, incidentally, runs all field initializers after the base class constructor completes, but before anything in the derived class constructor (other than the chain to the base constructor). This means that virtual methods have to be aware that field initializers may not have run, but also means that field initializers can make use of the object under constructions (which they cannot do in C#).
Incidentally, in VB.net, it's possible, though clunky, for a class to safely initialize fields with newly-created IDisposable instances (and ensure they will get disposed if the any part of the construction process throws an exception). In C#, one must refrain from using field initializers to create anything that cannot be safely abandoned if construction throws an exception, since there will be no way to access the partially-constructed object to clean it up.
using System;
class Parent
{
public Parent () {
Console.WriteLine("Hey Its Parent.");
}
}
class Derived : Parent
{
public Derived () {
Console.WriteLine("Hey Its Derived.");
}
}
class OrderOfExecution {
static void Main() {
Derived obj = new Derived();
}
}
The output from this program is shown here:
Hey Its Parent.
Hey Its Derived.
Constructor acts differently in Inheritance bit confusing for new Programmers. There are two concepts in execution of constructor
1. Calling
2. Execution
When you create a object of your derived class Named Derived the constructor first goes to Derived() then it goes to Parent() because of its calling.
Constructor calling is done from Bottom to Top but then you find it Executes Parent() first then Derived , that is because of its Execution.
Constructors Executed from Top to Bottom. That's why it print Parent first then Base while base constructor called first.

Multilevel inheritance constructor in C#

Is there a way in C# to call the grandfather's constructor? Let's say I have:
public class A
{
public A(parameterX x)
{
doSomething();
}
}
public class B : A
{
public B(parameterX x) : base(x)
{
doSomethingElse();
}
}
And then I have:
public class C : B
{
}
And I want the constructor in C to call the constructor in A, what can I use for this?
Is there something like:
public C(parameterX x) : base : base(x)
Or how can I just call the constructor in A from C?
Thanks.
You cannot call a grandparent class' constructor.
However, you don't need to either, since the base class already does.
When you write public C(parameterX x) : base(x), it will call B(x), which will in turn call A(x).
In general, since your base class' constructor will always call its base constructor (your grandparent), it wouldn't make sense to be able to explicitly call the grandparent constructor, since that would end up constructing it twice.
Although I don't really understand what is that you are trying to do and you probably can come up with a better actual design, you can probably achieve what you need by adding another constructor in B that takes the Bar parameter as A, but do nothing in it simply calling A(Bar) constructor, that way when you do C(bar) : base(bar) it will go to B and then to A. Ugly as hell.

Can I call an overloaded constructor from another constructor of the same class in C#?

Can I call an overloaded constructor from another constructor of the same class in C#?
No, You can't do that, the only place you can call the constructor from another constructor in C# is immediately after ":" after the constructor.
for example
class foo
{
public foo(){}
public foo(string s ) { }
public foo (string s1, string s2) : this(s1) {....}
}
If you mean if you can do ctor chaining in C#, the answer is yes. The question has already been asked.
However it seems from the comments, it seems what you really intend to ask is
'Can I call an overloaded constructor from within another constructor with pre/post processing?'
Although C# doesn't have the syntax to do this, you could do this with a common initialization function (like you would do in C++ which doesn't support ctor chaining)
class A
{
//ctor chaining
public A() : this(0)
{
Console.WriteLine("default ctor");
}
public A(int i)
{
Init(i);
}
// what you want
public A(string s)
{
Console.WriteLine("string ctor overload" );
Console.WriteLine("pre-processing" );
Init(Int32.Parse(s));
Console.WriteLine("post-processing" );
}
private void Init(int i)
{
Console.WriteLine("int ctor {0}", i);
}
}
EDIT: According to the comments on the original post this is a C# question.
Short answer: yes, using the this keyword.
Long answer: yes, using the this keyword, and here's an example.
class MyClass
{
private object someData;
public MyClass(object data)
{
this.someData = data;
}
public MyClass() : this(new object())
{
// Calls the previous constructor with a new object,
// setting someData to that object
}
}
In C# it is not possible to call another constructor from inside the method body.
You can call a base constructor this way: foo(args):base() as pointed out yourself.
You can also call another constructor in the same class: foo(args):this().
When you want to do something before calling a base constructor, it seems the construction of the base is class is dependant of some external things. If so, you should through arguments of the base constructor, not by setting properties of the base class or something like that

Categories

Resources