calling base constructor passing in a value - c#

public DerivedClass(string x) : base(x)
{
x="blah";
}
will this code call the base constructor with a value of x as "blah"?

The base call is always done first, but you can make it call a static method. For example:
public Constructor(string x) : base(Foo(x))
{
// stuff
}
private static string Foo(string y)
{
return y + "Foo!";
}
Now if you call
new Constructor("Hello ");
then the base constructor will be called with "Hello Foo!".
Note that you cannot call instance methods on the instance being constructed, as it's not "ready" yet.

No, base call we be performed before executing the constructor body:
//pseudocode (invalid C#):
public Constructor(string x) {
base(x);
x = "blah";
}

No, the base constructor is always called before the current constructor.

No, it will call it with the value passed into the derived class constructor. Base class constructor is always called (explicitly or implicitly) prior to executing the body of the derived class constructor.

No, It won't. The base constructor will be passed the string in x before the execution of DerivedClass constructor. This may work:
public DerivedClass(string x) : base("Blah")
{ }
I'm not sure about that but you should be able to call any method / getter when calling the base constructor, like that:
public DerivedClass(DateTime x) : base(DateTime.Now)
{ }

Related

Why do we have to pass values from derived class constructor to base class constructor

namespace Sample
{
public class Program
{
static int x;
public Program(int Y) {
x = Y;
Console.WriteLine("one value base class constructor called");
}
static void Main(string[] args)
{
Program prog = new s(10);
Console.ReadKey();
}
}
public class s: Program {
public s(int k):base(10)
{
Console.WriteLine("derived class constructor called");
}
}
}
Why is the base class constructor called first? If I have a parameterized constructor defined in the base class, then it is mandatory for the derived class constructor to pass the values to base class constructor from derived class.
I wanted to know the reason why it is mandatory? If no values are passed to the base class constructor then compiler gives the error message saying 'there is no argument given that corresponds to the required formal parameter'.
I am not asking whether or not I have to pass the values to base class but my question is why do I have to do that? Why is the that the base class constructor is to be called first?
You've answered your own question:
As we all know that the base class constructor is called before the derived class constructor.
Since your base class only have a constructor that must accept a parameter, you must supply this parameter when calling it.
If your base class would have a parameter-less constructor, then the compiler would be happy with public s(int k):base(), or even just public s(int k) (since base() will be added implicitly at compile time).
However, since you explicitly wrote a constructor to class Program, the compiler does not provide the default, parameter-less constructor, and therefor the only way to instantiate the Program class is by calling it's only constructor and passing the relevant parameter.

Base Classes constructor being hit without calling it?

Given the code:
public class A
{
public A()
{
throw new Exception();
}
}
public class B : A
{
public B(int i)
{
}
}
Then running the line:
var x = new B(2);
I would never expect A's constructor to get hit (unless I added base()) to the end of B's constructor declaration.
Oddly it seems to be getting hit (and throwing the exception). Is this default behavior? This has caught me out as I fully never expected A's constructor to be hit
If you don't include any base(..) or this(..), it does the same thing as if you had base(). From the C# spec:
If an instance constructor has no constructor initializer, a constructor initializer of the form base() is implicitly provided. Thus, an instance constructor declaration of the form
C(...) {...}
is exactly equivalent to
C(...): base() {...}
You might've been looking to make A an abstract class, so that you cannot directly create an instance of A.
public abstract class A
{
}
public class B : A
{
public B(int i)
{
}
}
public static void Main()
{
// A a = new A(); // doesn't compile
A a = new B(2); // valid
}
But within B class inherited by A class.so when you create on B instance ,automatically initiate the A instance as well.This is the default behavior in OOP concept.
This is the default behaviour. Constructors run in order from base class first to inherited class last. When you write base() then you can pass some value directly to base constructor
for eg
public class B : A
{
public B(int i): base(i)
{
}
}
As your commentors have mentioned, this is the default C# behavior. A constructor on each base class MUST be called.
If your rule is that ClassA should never be constructed (only child classes), declare ClassA as abstract
public abstract class A {}
With that syntax, it will be a compile-time error if you attempt to construct an A (but B will be ok), so you can remove the throw in A's constructor.
That's expected: if you don't explicitly specify a different overload of a constructor, it will always be invoked by default. And even if you do specify a different overload to call, it will also propagate to its base class' constructor until it reaches the root Object() constructor.
Note that this also means that if you have a different constructor overload in a single class, instantiating the object through the overloaded constructor will not call the parameterless constructor of that same class, but instead the parameterless constructor of the base class (in this case, Object()):
public class A
{
public A()
{
throw new Exception();
}
public A(int i)
{
// this will not call the A(), but the base Object() constructor
}
}
var a = new A(5); // no exception thrown

Automatically call superclass method in constructor

Is there a way in C# to guarantee that a method of a superclass will be automatically called by every subclass constructor?
Specifically, I am looking for a solution that only adds code to the superclass, so not "base(arguments)"
The only way to guarantee it is to make the call in the constructor of the base class. Since all subclasses must call a constructor of the base, your method of interest will be called as well:
class BaseClass {
public void MethodOfInterest() {
}
// By declaring a constructor explicitly, the default "0 argument"
// constructor is not automatically created for this type.
public BaseClass(string p) {
MethodOfInterest();
}
}
class DerivedClass : BaseClass {
// MethodOfInterest will be called as part
// of calling the DerivedClass constructor
public DerivedCLass(string p) : base(p) {
}
}

What is the code : base()

What is the purpose of base() in the following code?
class mytextbox : TextBox
{
public mytextbox() : base()
{
this.Text = "stack";
}
}
Why At design time messages are displayed ؟
my code :
class Class1:TextBox
{
public Class1()
{
this.Resize += new EventHandler(Class1_Resize);
}
void Class1_Resize(object sender, EventArgs e)
{
MessageBox.Show("Resize");
}
}
base() in your code is a call to the parameterless constructor of the base-class ofmyTextBox, which happens to beTextBox. Note that this base constructor will execute before the execution of the body of the constructor in the derived class.
Every class's constructor must eventually call one of its base class's constructors, either directly or through chained constructors in the same class. Consequently, there is always an implicit / explicit base(...) or explicit this(...) call on every constructor declaration. If it is omitted, there an implicit call to base(), i.e. the parameterless constructor of the base class (this means that the call tobase()in your example is redundant). Whether such a declaration compiles or not depends on whether there exists such an accessible constructor in the base class.
EDIT:
Two trivial points:
The root of the class-hierarchy does not have a base class, so this rule does not apply to System.Object's only constructor.
The first sentence should read: "every non-System.Object class's constructor that completes successfully must eventually call one of its base class's constructors." Here is a 'turtles all the way down' example where the base class's contructor is never called: instantiating an object of such a class will obviously overflow the execution-stack.
// Contains implicit public parameterless constructor
public class Base { }
// Does not contain a constructor with either an explicit or implicit call to base()
public class Derived : Base
{
public Derived(int a)
: this() { }
public Derived()
: this(42) { }
static void Main()
{
new Derived(); //StackOverflowException
}
}
No idea, it is unnecessary. A constructor always calls the base class constructor automatically without you having to write it explicitly. But that's what it means. You'd have to write it if you don't want to call the parameterless constructor but one that takes an argument.

How can I tell the inheriting class to not call its base class' parameter-less constructor?

I was surprised to find out that the parameter-less constructor of my base class is called any time I call any constructor in a derived class. I thought that is what : base() was for, to explicitly call the base constructor if and when I want to.
How can I prevent the base constructor from being called when I instantiate a derived class?
using System;
namespace TestConstru22323
{
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer("Jim", "Smith");
Customer c = new Customer();
Console.WriteLine(customer.Display());
Console.ReadLine();
}
}
public class Person
{
public Person()
{
Console.WriteLine("I don't always want this constructor to be called. I want to call it explicitly.");
}
}
public class Customer : Person
{
private string _firstName;
private string _lastName;
//public Customer(string firstName, string lastName): base() //this explicitly calls base empty constructor
public Customer(string firstName, string lastName) //but this calls it anyway, why?
{
_firstName = firstName;
_lastName = lastName;
}
public string Display()
{
return String.Format("{0}, {1}", _lastName, _firstName);
}
}
}
The only way is to explicitly tell it which other base ctor you want it to call; which of course means you must choose some base ctor to call.
You can't have it call no base ctor at all - conceptually, constructing a Customer is done by first constructing a Person, and then doing Customer specific construction on top of it. For example, suppose Person had private fields - how would these be correctly constructed if construction of a Customer was allowed to not first construct a Person?
In .NET, every object constructor in an object hierarchy will be called regardless if you call :base() or not.
:base() is implicitly called if you don't explicitly call it.
:base() can be used if you want to call a different contructor on a parent object rather than the default constructor.
If you have code in the parent constructor that should not be called everytime, it may be better to move that code to it's own method that will need to be called explicitly after the object is constructed. Or, create a parameterized constructor on the parent object and use the parameter to determine if the code should be executed or not.
For example:
:base(true) - This executes your code.
:base(false) - This does not execute your code.
As others have pointed out, a derived instance must call call one of its base class' constructors.
If you want to control the execution of a base class' initialization logic, remove its default constructor and replace it with something like this:
public class Base {
// Base has no default constructor
public Base(bool initialize) {
if (initialize) {
// ... logic here
}
}
}
And the derived constructors look like this:
// Derived1 executes the initialization logic
public Derived1(): base(true) {}
// Derived2 does not
public Derived2(): base(false) {}
You could make the default base constructor protected, then have only non-default constructors for the base and its child.
edit
You could give the base a protected constructor with a different signature (such as a protected enum type), and put your initialization code in there, while the default constructor, also protected, does not particular initialization.
Your requirement to only need to call the constructor for some derived objects is not in line with the object-oriented principles. If it's a Person, then it needs to be constructed as such.
If you need shared initialization for some objects, then you should consider creating an Initialize method or adding a parameterized constructor that will be called by the specific derived objects.
The parameterized constructor approach feels a little awkward:
public abstract class Person
{
protected Person()
{
}
protected Person( bool initialize )
{
if (initialize)
{
Initialize();
}
}
// ...
}
public class Customer : Person
{
public Customer(string firstName, string lastName)
{
// ...
}
}
public class Employee : Person
{
public Customer(string firstName, string lastName) : base(true)
{
// ...
}
}
When you instantiate a class all the classes in the inheritance hierarchy are instantiated starting from the topmost Parent to the lowermost child, stopping at the type you instantiated. So if you instantiate System.Text.StringBuilder(), first you call the default constructor of System.Object, then StringBuilder(). You can use the base keyword to call a different constructor (one with equal or fewer params), but not more params. If you do not specify base, the default constructor is called, thus the reason this is happening to you. You can also use the base keyword within the context of an instance method to call base implementations, such as in the case of the decorator pattern. If you do not want to call the base class private constructors then you should set the children with private default constructors and also explicitly call base(params) on your other constructors.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class ProcessCaller
{
static void Main()
{
MyDerived md1 = new MyDerived(1);
object o = new System.Text.StringBuilder();//This will implicitly instantiate the classes in the inheritance hierarchy: object, then stringbuilder
}
}
public class MyBase
{
int num;
public MyBase()
{
Console.WriteLine("in MyBase()");
}
public MyBase(int i )
{
num = i;
Console.WriteLine("in MyBase(int i)");
}
public virtual int GetNum()
{
return num;
}
}
public class MyDerived: MyBase
{
//set private constructor. base(i) here makes no sense cause you have no params
private MyDerived()
{
}
// Without specifying base(i), this constructor would call MyBase.MyBase()
public MyDerived(int i) : base(i)
{
}
public override int GetNum()
{
return base.GetNum();//here we use base within an instance method to call the base class implementation.
}
}
}
One way would be to make your base default constructor private, but that only works if you make a helper constructor in the base class that calls the private one when you need it explicitly.
class Base
{
private Base() { ... special default base logic ... }
protected Base(... params ...) : this() { ... exposed base that calls private cons ... }
protected Base(... other params ...) /* no default call */ { ... exposed cons that doesnt call default ...}
}
class DerivedNoCall
{
public DerivedNoCall() : base(... other params ...) {} //<-- will NOT call default base
}
class DerivedDoCall
{
public DerivedDoCall() : base(... params ...) {} //<-- WILL call default base cons indirectly
}
This is really contrived, and #aakashm has the best answer.

Categories

Resources