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.
Related
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
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.
What is the reason for initialization using constructor instead of method.
Code 1:
class A {
int x, y;
public A() {
x = 10;
y = 4;
}
}
Code 2:
class A {
int x, y;
public fun() {
x = 10;
y = 4;
}
}
From above, what is the difference between Code 1 and Code 2.
If any one know the answer please clear my doubt.?
It is guaranteed that constructor will get called when object is created but in case of method it is your control when to call. If you initialize values in method instead of constructor, there may be side effect if you call the method at wrong time.
Therefore it is always good practice to initialize the values in constructor instead of methods and that is the purpose of constructor.
First assignment occurs when instance is created. Second assignment occurs when you will execute the fun() method.
BTW you can call fun() method in constructor.
A constructor ensures that the object is properly instantiated. There's not guarantee that the caller will call the method to manually instantiate the object.
the constructor is called to create the instance of your class and does not rely on calls, unlike the method
When using code 1, A a = new A(); will init x and y.
When using code 2, you need A a = new A(); and a.fun(); to init x and y.
Init of your variables should be placed within a method if you wanna use this method also for additional inits sometime later.
btw fun is not an adequate name for a method.
A constructor is implicitly called when an object is created. In second case, the method is an instance level method.. You will have to create an object of type A and then "change" the values of x and y... The defualt constructor will assign default value (0) to your int variables...
Constructor used as initializer , because of it provide the functionality to initializing the object to memory or when a object is created at that time constructor will call first. If you don't initialize any value separately and you want to use some variable in your result then you can use constructor as initializer.
Why constructor use in coding? Bcz it have the nature to initialize some thing before of creation of Object.
I think you got my point. happy learning. :)
Thanks
Technically, you can hide constructor and use factory method pattern:
class A {
int x, y;
// Hidden constructor
protected A() {
x = 10;
y = 4;
}
// Factory method to create A class instances
public static A Create() {
...
A result = new A();
...
return result;
}
}
In your example factory method is an overshoot, but it could be helpful
when implementing singleton, strategy patterns etc.
This question already has answers here:
Call one constructor from another
(13 answers)
Closed 9 years ago.
I saw this code block when i was trying build something with APN. Could someone explain me what does "this" statements do there ?
public ApplePushService(IPushChannelFactory pushChannelFactory, ApplePushChannelSettings channelSettings)
: this(pushChannelFactory, channelSettings, default(IPushServiceSettings))
Is it like default values of those arguments ?
this calls the overloaded constructor for the ApplePushService class with the specified parameters.
For example
// Set a default value for arg2 without having to call that constructor
public class A(int arg1) : this(arg1, 1)
{
}
public class A(int arg1, int arg2)
{
}
This lets you call one constructor that can invoke another.
Sure - that chains one constructor onto another. There are two forms - this to chain onto another constructor in the same class, and base to chain to another constructor in the base class. The body of the constructor you're chaining to executes, and then your constructor body executes. (Of course, the other constructor may chain onto another one first.)
If you don't specify anything, it automatically chains to a parameterless constructor in the base class. So:
public Foo(int x)
{
// Presumably use x here
}
is equivalent to
public Foo(int x) : base()
{
// Presumably use x here
}
Note that instance variable initializers are executed before the other constructor is called.
Surprisingly, the C# compiler doesn't detect if you end up with mutual recursion - so this code is valid, but will end up with a stack overflow:
public class Broken
{
public Broken() : this("Whoops")
{
}
public Broken(string error) : this()
{
}
}
(It does prevent you chaining onto the exact same constructor signature, however.)
For more details, see my article on constructor chaining.
That is calling another constructor in that case, the : this(...) is used to call another constructor in that class.
For example:
public ClassName() : this("abc") { }
public ClassName(string name) { }
EDIT:
Is it like default values of those arguments ?
It an overload you can delegate it's full logic in one place and call from the rest of the constructors with default values.
this keyword can be used in these contexts:
Call other constructors.
Passing the current object as a parameter.
Refer to instance methods or fields.
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