Computing values before calling base constructor - c#

Is there any way in which you can call super constructor at the end of descendant class constructor?
It works in Java, but in C# the keyword base doesn't seem to be equivalent to Java's super.
Example:
class CommonChest : BasicKeyChest
{
public CommonChest()
{
Random rnd = new Random();
int key = rnd.Next(1, 6);
int coins = rnd.Next(70, 121);
super(key, coins, "Common");
}
}

There is no way to postpone the call to the base constructor, it must complete before the derived constructor starts.
However, you can perform computations outside the derived constructor prior to calling the base constructor by providing an expression that you pass to the base:
class CommonChest : BasicKeyChest {
public CommonChest()
: this(GenTuple()) {
}
private CommonChest(Tuple<int,int> keysCoins)
: base(keysCoins.Item1, keysCoins.Item2, "Common") {
}
private static Tuple<int,int> GenTuple() {
Random rnd = new Random();
int keys = rnd.Next(1, 6);
int coins = rnd.Next(70, 121);
return Tuple.Create(keys, coins);
}
}
The above is a little tricky: a private constructor that takes a pair of ints is used to forward these ints to the base constructor. The tuple is generated inside GenTuple method, which is invoked before calling the base constructor.

NO, the concept of using base keyword or Constructor Initializer is that the base constructor gets called first and then child constructor. So that all common or shared parameters across the childs gets initialized first and then specific properties of child classes. That's also one of the reason why an abstract class can have Constructor

You could call a static method within the call to the base constructor:
class CommonChest : BasicKeyChest
{
public CommonChest() : base(DoSomething())
{
}
private static Tuple<int,int> DoSomething()
{
Random rnd = new Random();
int key = rnd.Next(1, 6);
int coins = rnd.Next(70, 121);
return Tuple.Create(key, coins);
}
}

This design avoids that you access a member from the base-class within your derived constructor although it has not been yet initialized as it´s base-class constructor wasn´t called.
Imagine this was possible:
class MyClass
{
MyClass()
{
var a = base.MyBaseProperty;
base();
}
}
What will a be before the call to base()? As myBaseProperty is declared in the base-class it would be unitialized if the base-class constructor wasn´t the very first statement.
Furthermore the compiler will inform you if you forgot about the call to base(...) so that you can´t accidentally run your constructor without calling the base-class´ one.

Related

C# - When i try to create constructor, i get CS7036 error

Firstly, sorry for my English. I hope i can explain my problem.
I have class like this
public class CarCommandExecutorBase
{
protected readonly ICarCommand CarCommand;
public CarCommandExecutorBase(ICarCommand carCommand)
{
CarCommand = carCommand;
}
}
Also i have class like this
public class CarStringCommandExecutor : CarCommandExecutorBase, IStringCommand
{
public CarStringCommandExecutor(Car car)
{
// this Constructor gives me an error.
}
public void ExecuteCommand(string commandObject)
{
}
}
Error message:
[![error][1]][1]
What's the reason and how can i fix it? Thanks.
Since the only constructor in CarCommandExecutorBase is defined like this
public CarCommandExecutorBase(ICarCommand carCommand)
{
CarCommand = carCommand;
}
you have to pass an ICarCommand when creating an instance of CarCommandExecutorBase.
You have to provide an ICarCommand through the constructor of CarStringCommandExecutor, because when instantiating a derived type the base constructor(s) also get called.
See this answer for more detailed information about this: https://stackoverflow.com/a/1882778/8450550
You could do something like this to solve this error:
public class CarStringCommandExecutor : CarCommandExecutorBase, IStringCommand
{
...
public CarStringCommandExecutor(Car car, ICarCommand carCommand)
: base(carCommand) // base() points to the constructor of the base class
{
...
}
or maybe this
public class CarStringCommandExecutor : CarCommandExecutorBase, IStringCommand
{
...
public CarStringCommandExecutor(Car car)
: base(null) // passing null but be aware of NullReferenceExceptions
{
...
}
or you add another constructor to CarCommandExecutorBase which expects no arguments:
public class CarCommandExecutorBase
{
protected readonly ICarCommand CarCommand;
public CarCommandExecutorBase(ICarCommand carCommand)
{
CarCommand = carCommand;
}
// mark this constructor as protected, so only deriving types can call it
protected CarCommandExecutorBase()
{
}
}
Which solution works best in your case is up to you.
One of the things that isn't immediately apparent, thanks to "compiler magic", about a C# class is that every class has a constructor
It needs to be this way because it's a rule that object construction happens in a tree; you construct some class Z which inherits from Y which inherits from X which inherits from object, and Z's cosntructor invokes Y's invokes X's invokes object's, then they finish, in order of object, X, Y, Z and you have your nicely constructed thing - every constructor on the way up the tree had its chance to do its init and ready the object for use (the part of it that each constructor was responsible for)
Even classes that don't seem to have constructors, have constructors:
class X {
}
If you don't provide a constructor, C# provides one for you. You never see it in your source code; just imagine that in between reading the file and compiling it, the compiler inserts it for you. It takes no parameters, has no code, and does nothing other than call its base:
class X {
X():base() { } //C# invisibly writes this for you
}
If you provide a constructor but don't write the base... bit, C# puts base() in for you behind the scenes (and it always calls the no-argument base()) but critically it doesn't provide an empty constructor if you provided one already
This means if you have a class like:
class X{
X(string message){
...
}
}
Your class X has a constructor, so C# won't provide the empty one, so now anything that tries to construct your class must provide a string message:
X x = new X("hello");
If you now inherit from X, you might do one of 3 things (with Y):
class Y:X{
}
You don't add a constructor, C# adds one, but it just dumbly calls base(), which doesn't work because there is no constructor in X that takes no args:
class Y:X{
Y():base() { }
}
You add a constructor but leave off the base bit. C# adds it, again just literally as base() - this also doesn't work for the same reason
class Y:X{
Y(int myArg) //c# adds base() in here for you
{
...
}
}
You add a constructor that includes a call to base and because you know your base class only has a constructor with a string arg, you pass one:
class Y:X{
Y(int myArg) : base("hello")
{
...
}
}
So you're in scenario 2, and you either need to:
Add a no-arg constructor to the base class so that c#'s auto-inserted stuff works or,
Add a call to base(...) with a suitable argument, to stop C# from putting a base() in
I've left out access modifiers from code in this answer for clarity of demonstrating the essential point. Whether a constructor is accessible or not can also have a bearing on all this, but I deemed it out of scope

Why child class variable initialize before parent class member variable

Consider the code below. Fields i and j are initialized before m and n. We know that the parent object is created before the child object, but in my program the compiler is allocating and initializing memory for the child class' member variables before the base class'. Why is that?
class X
{
private int m = 0;
private int n = 90;
public X() { }
}
class Y:X
{
private int i = 8;
private int j = 6;
public Y()
{ }
public static void Main(string []args)
{
Y y1 = new Y();
}
}
This is explained in Eric Lippert's blog:
[...] an initialized readonly field is always observed in its initialized state, and we cannot make that guarantee unless we run all the initializers first, and then all of the constructor bodies.
Not sure why readonly is mentioned here, but for example, this ensures that the following scenarios, albeit being stupid, work:
1.
class Base
{
public Base()
{
if (this is Derived) (this as Derived).Go();
}
}
class Derived : Base
{
X x = new X();
public void Go()
{
x.DoSomething(); // !
}
}
2.
class Base
{
public Base()
{
Go();
}
public virtual Go() {}
}
class Derived : Base
{
X x = new X();
public override void Go()
{
x.DoSomething(); // !
}
}
This order is explicitly stated in C# Language Specification (17.10.2):
[...] constructor implicitly performs the initializations specified by the variable-initializers of the instance fields declared in its class. This corresponds to a sequence of assignments that are executed immediately upon entry to the constructor and before the implicit invocation of the direct base class constructor.
This is one of those rare places where an understanding of procedural methodology makes object-oriented methodology easier to understand. Even though you're working OOP, the compiler still adheres to procedural logic - working start to finish.
A simple example is when the compiler hits private int n = 90. First it allocates space for an integer value, then an identifier to access it as an integer, then assigns it the value of 90. It can't assign the value until it both has the space to stick it AND knows how to access it, nor can it access non-existent space.
In this instance, your derived class Y is built atop the base class X, similar to how the variable n is built atop the "class" integer in the example above. This is triggered by the declaration class Y:X - the compiler can't even start building Y until it understands how to build X.
Child construction code must be allowed to call functions on the parent, which can't work unless the parent is already fully-constructed.
However, the objects share the same memory block. So all the memory is allocated in one go, then the classes are initialized working up the class hierarchy.

Is this syntax valid?

I have a class in C# that has two constructors
public class GObject {
public GObject(){
// The default constructor
}
public GObject(int xPos, int yPos){
// Second constructor
}
}
Is this valid to write a sub-class Block like this?
public class Block : GObject {
// Sub class methods go here, no special constructor
}
And instantiate Block with the 2nd constructor?
Block myBlock = new Block(10, 15);
Since you don't have a two parameter constructor defined on Block, you can't write your final line - it will not compile.
You can have a chained constructor on Block:
public Block(int xPos, int yPos) : base(xPos, yPos)
{}
In which, case:
Block myBlock = new Block(10, 15);
Will work just fine.
By default, if you do not write the constructor explicitly; compiler creates a default constructor with no parameters.
In your case, since Block does not have any constructors defined, only parameterless constructor is created. Thus, you can not create a Block object using two parameters.

C#: Order of Constructor call

Consider the following code:
The code
public class RecursiveConstructor
{
//When this constructor is called
public RecursiveConstructor():this(One(), Two())
{
Console.WriteLine("Constructor one. Basic.");
}
public RecursiveConstructor(int i, int j)
{
Console.WriteLine("Constructor two.");
Console.WriteLine("Total = " + (i+j));
}
public static int One()
{
return 1;
}
public static int Two()
{
return 2;
}
}
The calling method
public class RecursiveConstructorTest
{
public static void Main()
{
RecursiveConstructor recursiveConstructor = new RecursiveConstructor();
Console.ReadKey();
}
}
The Result
Constructor two.
Total = 3
Constructor one. Basic.
Why is the 2nd constructor run first?
I understand that in chained constructors we call the base class constructor first and then make our way back up the chain but when the constructor is held in the same class why do we still see this behaviour where the extra constructor is called first?
I would have thought that the most basic constructor contents would be executed first.
I think the compiler runs the safer scenario.
If you call another constructor here, there are chances that this other constructor is a prerequisite to your current constructor. This behaviour is consistent with the one exposed when calling base constructors, and is then to be expected.
When creating a new instance of a class, there is a chain of constructors that get called from the least specialized (the constructor of the object class) to the most specialized (the constructor of your current class).
The operator : allows you to explicitly add a constructor to this chain, so this order seems natural.
You gave the explanation yourself. It is almost the same way base constructors are called. Whenever calling a constructor in your signature, like
public RecursiveConstructor() : this(One(), Two())
or
public RecursiveConstructor() : base()
the constructor right after the : is called first.
It makes sense when you consider that there is always a hierarchical chain of constructor calls when initializing new objects. As you rightly say, the base classes constructor is called first.
The two forms of constructor initializer, : base(...), which is often implictly called, and : this(...) behave the same way.
So, in your case we have a chain:
Object()
then...
RecursiveConstructor(int i, int j)
then...
RecursiveConstructor()
It is calling constructor 1 first, but ctor1 is calling ctor2 before it hits the ctor1 code block, hence the output you see.
One way around this, but to retain the DRY behaviour would be to refactor the (int, int) overload:
//When this constructor is called
public RecursiveConstructor()
{
Console.WriteLine("Constructor one. Basic.");
Init(One(), Two());
}
public RecursiveConstructor(int i, int j)
{
Console.WriteLine("Ctor 2");
Init(i, j);
}
private void Init(int i, int j)
{
Console.WriteLine("Refactored");
Console.WriteLine("Total = " + (i+j));
}
Out of interest, chaining constructors this way is often referred to as 'delegating constructors'.
In Java, it is possible to place the call to the other constructor in the code block (e.g. see here), but it must be the first line in the block

What is the need of private constructor in C#?

What is the need of private constructor in C#?
I got it as a question for a C# test.
For example if you have a class that should only be created through factory methods. Or if you have overloads of the constructor, and some of them should only be used by the other constructors. Probably other reasons as well =)
If you know some design pattern, it's obvious: a class could create a new instance of itself internally, and not let others do it.
An example in Java (I don't know C# well enough, sorry) with a singleton-class:
class Meh
{
private Meh() { }
private static Meh theMeh = new Meh();
public static Meh getInstance() { return theMeh; }
}
Whenever you want to prevent direct instantiation of a class from outside of it, you'll use a private constructor. For example, prior to C# 2.0 which introduced static classes, you used a private constructor to accomplish roughly the same thing:
sealed class StaticClass {
private StaticClass() {
}
public static void DoSomething() {
}
}
When you want to prevent the users of your class from instantiating the class directly. Some common cases are:
Classes containing only static methods
Singletons
I can can recall few usages for it:
You could use it from a static factory method inside the same class
You could do some common work inside it and then call it from other contructure
You could use it to prevent the runtime from adding an empty contructure automatically
It could be used (although private) from some mocking and ORM tools (like nhibernate)
For example when you provide factory methods to control instantiation...
public class Test(){
private Test(){
}
void DoSomething(){
// instance method
}
public static Test CreateCoolTest(){
return new Test();
}
}
Private constructors are used to prevent the creation of instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class. If all the methods in the class are static, consider making the entire class static. For more information see Static Classes and Static Class Members.
class NLog
{
// Private Constructor:
private NLog() { }
public static double e = System.Math.E; //2.71828...
}
The following is an example of a class using a private constructor.
public class Counter
{
private Counter() { }
public static int currentCount;
public static int IncrementCount()
{
return ++currentCount;
}
}
class TestCounter
{
static void Main()
{
// If you uncomment the following statement, it will generate
// an error because the constructor is inaccessible:
// Counter aCounter = new Counter(); // Error
Counter.currentCount = 100;
Counter.IncrementCount();
System.Console.WriteLine("New count: {0}", Counter.currentCount);
}
}
While this link is related to java, I think it should help you understand the reason why as the idea is pretty much the same.
Private constructors prevent a class from being explicitly instantiated by callers. There are some common cases where a private constructor can be useful:
classes containing only static utility methods
classes containing only constants
type safe enumerations
singletons
You can use it with inheritance in a case where the arguments to the constructor for the base class are of different types to those of the child classes constructor but you still need the functionality of the base class in the child class eg. protected methods.
Generally though this should be avoided wherever possible as this is a bad form of inheritance to be using.
I'm late to the game, but reading through all the other answers, I don't see this usage mentioned:
I use private constructors in scenarios where I have multiple (public) constructors, and they all have some code in common. With constructor chaining, the code becomes really neat and DRY.
Remember, the private readonly variables can only be set in constructors, so I can't use a regular method.
Example:
public class MyClass
{
private readonly int _a;
private readonly int _b;
private readonly string _x;
public MyClass(int a, int b, string x)
: this(x)
{
_a = a;
_b = b;
}
public MyClass()
: this("(not set)")
{
// Nothing set here...
}
private MyClass(string x)
{
_x = x;
}
}
Basically you use private constructors when you are following a singleton design pattern. In this case, you have a static method defined inside the class that internally calls the private constructor.
So to create the instance of the class for the first time, the user calls the classname.static_method_name. In this method, since the class's object doesn't yet exist, the static method internally calls the private constructor and returns the class's instance.
If the class's instance already exists, then the static method simply returns the instance to the calling method.
And of course you can use private constructor to prevent subclassing.

Categories