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.
Related
In what situations should I execute a constructor of the parent class for a child class? And why use the "base" reserved word?
Exemple:
The constructor of the base class is always called. Or more exact, one constructor of the base class. If you don't specify which one (by using the base reserved word), the default constructor of the base class is called (that means the one with no arguments). If the base class has no constructor without arguments, a compiler error occurs. With the base keyword, you specify that you want to call a certain constructor. Here are some simple examples:
public class Base
{
private int _a;
public Base() // default ctor
{_a = 0;}
public Base(int a) // a ctor with an argument
{_a = a;}
}
public class Derived : Base
{
public Derived() : base(2) // call the ctor with argument "2"
{}
public Derived(bool b) // uses the ctor without argument of the base class (_a will stay 0)
{
}
}
The keyword base here is used as a generic placeholder for the name of the base class. The only other word syntactically allowed there would be this (if you want to call a constructor of the same class)
If you not use :base word for child constructor.
Default constructor of parent will be executed.
If you have some basic construnctor in base class and you have some fields in it and want to fill it using basic constructor you should use base keyword.
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.
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
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) {
}
}
I have a class like below
public abstract class ABC
{
int _a;
public ABC(int a)
{
_a = a;
}
public abstract void computeA();
};
Is it mandatory for the derived class to supply the parameters for the base/abstract class constructor? Is there any way to initialize the derived class without supplying the parameters?
Thanks in advance.
Yes, you have to supply an argument to the base class constructor.
Of course, the derived class may have a parameterless constructor - it can call the base class constructor any way it wants. For example:
public class Foo : ABC
{
// Always pass 123 to the base class constructor
public Foo() : base(123)
{
}
}
So you don't necessarily need to pass any information to the derived class constructor, but the derived class constructor must pass information to the base class constructor, if that only exposes a parameterized constructor.
(Note that in real code Foo would also have to override computeA(), but that's irrelevant to the constructor part of the question, so I left it out of the sample.)
You can create a default constructor in a derived class that does not need parameters and the derived class will supply default values, but you cannot remove the requirement entirely. It is a manadatory condition of the base class to have some sort of value.
public MyDerivedClass : ABC
{
public MyDerivedClass()
: base(123) // hard wired default value for the base class
{
// Other things the constructor needs to do.
}
public override void computeA()
{
// Concrete definition for this method.
}
}
Add a default constructor to the base class and call the other constructor providing an initial values for its parameters:
public abstract class ABC
{
int _a;
public ABC(int a)
{
_a = a;
}
public ABC() : this(0) {}
}
It doesn't have much to do with the fact that the base class is abstract.
Because you've declared a public constructor that has 1 parameter, the compiler removes the basic empty constructor.
So, if you want to create an instance of that class, you have to pass a parameter.
When you derive from such a class, a parameter must be passed to the base class for it o construct.