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.
I have an abstract base class from which I derive two classes. The abstract class has a protected field which is initialized by constructors in the derived classes. Each of the derived classes has two constructors, the first constructor of each class initializes the field and the second constructor modifies the initialization of the first by calling the first constructor. The second constructor of both derived classes are exactly the same but the first constructor is different between the two derived classes. Is there some way to put the second constructor in the base class?
Here is an example to illustrate what I'm trying to say:
public abstract class A {
protected int[] field1;
public void someMethod() {
//somethingsomething
}
}
public class B : A {
public B() {
//body X
//this initializes field1 in some way
}
public B(bool p) : this() {
//body Y
//this initializes field1 in some way + modification
}
}
public class C : A {
public C() {
//body Z
//this initializes field1 in another way
}
public C(bool p) : this() {
//body Y
//this initializes field1 in another way + modification
}
}
What I would like to do, is to find some way so as to not have to repeat body Y twice. I was thinking of putting body Y of B(bool p) and C(bool p) in a constructor in class A as A(bool p), then have B(bool p) and C(bool p) call the base class constructor with : base(bool p) followed by an empty body, but then realized the base class constructor would have to call the derived class constructor.
This sounds stupid to me too. Although I am not sure, it's because I have this feeling that calling something from a derived class from a base class is something that can only be done at run time and there really is no way to check this at compile time. I'm just trying to find a way to follow the DRY principle.
Thanks.
Short answer: no. That would be breaking the object-oriented paradigm, so you wouldn't want to be able to do that anyway. Think about it this way: an abstract base class can be extended by an arbitrary number of classes, but if it was tightly coupled to one of the child classes, how would that impact the other ones?
public class BaseClass {
// Call child class constructor
public BaseClass() : A() { }
}
public class A : BaseClass {
public A() { ... }
}
// How should BaseClass handle this? There is no constructor named "A."
public class B : BaseClass {
public B() { ... }
}
If you want the base class and derived class to share some functionality, you should make it a protected method in the base class. That way, you can call that method from the constructor.
You could also make a constructor on the base class that provides the common functionality and call it from the child class with : base(...).
The only way a base class can trigger a derived behavior is through polymorphism (having a virtual method in B, and overriding it).
But there's some other way that might be much more inuitive in your case. For example:
public class C : A {
public C() {
//body Z
//this initializes field1 in another way
}
public C(bool p) : base(p) {
//this initializes field1 in another way + modification
}
}
Please note that in your example, B's default constructor calls A's default constructor, as well as C's default one calls B's default one.
Lastly, you can also consider having a second constructor in A that receives field1 initial value as a parameter, but it depends if your instructions are order-dependent.
If you precise what your constructors do exactly, I might have a more decisive answer for you.
Sincerely,
I have a set of classes that inherit from a base...
public abstract class BaseClass
{
public BaseClass()
{
// ...
}
}
public abstract class BaseMessageClass : BaseClass
{
// ...
}
public SpecificMessageClass : BaseMessageClass
{
// ...
}
Instantiating an object like this works:
SpecificMessageClass myMessage = new SpecificMessageClass();
However, I need to change all constructors to have an optional string parameter, like this:
public abstract class BaseClass
{
public BaseClass(string optParam="whatever")
{
// ...
}
}
Now, when I try and instantiate the object with the optional argument:
SpecificMessageClass myMessage = new SpecificMessageClass("coolstring");
I get the error:
'SpecificMessageClass' does not contain a constructor that takes 1 arguments"
Is there ANY way to do this without explicitly declaring the constructors in each level of inherited class?
No.
But given that you want to inherit, I'm guessing you want the same logic to apply at all levels on some inherited field or property. If so, the closest you can get is to add a factory method like a Create<T>(string optParam="whatever") on the base class like the following:
public class BaseClass
{
public static T Create<T>(string optParam="whatever") where T : BaseClass
{
var t = new T(); //which invokes the paramterless constructor
((BaseClass)t).SomePropertyOrFieldInheritedFromTheBaseClass = optParam; //and then modifies the object however your BaseClass constructor was going to.
return t;
}
}
That would allow all implementers of the class to implement the BaseClass and get the same effect as having the optional parameter constructor.
By the way, I didn't test the above code, so you might need to tweak it slightly. But hopefully it gives the idea.
I think that's probably the closest you can get.
Constructors are special methods. If your class specifies no constructors, it will have a no-args constructor that inherits from the parent's no-args constructor. As soon as you specify a single constructor, you do not automatically get any of the parent's constructors for free. You must declare each different constructor you need.
How and when to call the base class constructor in C#
You can call the base class constructor like this:
// Subclass constructor
public Subclass()
: base()
{
// do Subclass constructor stuff here...
}
You would call the base class if there is something that all child classes need to have setup. objects that need to be initialized, etc...
Hope this helps.
It's usually a good practice to call the base class constructor from your subclass constructor to ensure that the base class initializes itself before your subclass. You use the base keyword to call the base class constructor. Note that you can also call another constructor in your class using the this keyword.
Here's an example on how to do it:
public class BaseClass
{
private string something;
public BaseClass() : this("default value") // Call the BaseClass(string) ctor
{
}
public BaseClass(string something)
{
this.something = something;
}
// other ctors if needed
}
public class SubClass : BaseClass
{
public SubClass(string something) : base(something) // Call the base ctor with the arg
{
}
// other ctors if needed
}
I've got a (poorly written) base class that I want to wrap in a proxy object. The base class resembles the following:
public class BaseClass : SomeOtherBase
{
public BaseClass() {}
public BaseClass(int someValue) {}
//...more code, not important here
}
and, my proxy resembles:
public BaseClassProxy : BaseClass
{
public BaseClassProxy(bool fakeOut){}
}
Without the "fakeOut" constructor, the base constructor is expected to be called. However, with it, I expected it to not be called. Either way, I either need a way to not call any base class constructors, or some other way to effectively proxy this (evil) class.
There is a way to create an object without calling any instance constructors.
Before you proceed, be very sure you want to do it this way. 99% of the time this is the wrong solution.
This is how you do it:
FormatterServices.GetUninitializedObject(typeof(MyClass));
Call it in place of the object's constructor. It will create and return you an instance without calling any constructors or field initializers.
When you deserialize an object in WCF, it uses this method to create the object. When this happens, constructors and even field initializers are not run.
If you do not explicitly call any constructor in the base class, the parameterless constructor will be called implicitly. There's no way around it, you cannot instantiate a class without a constructor being called.
At least 1 ctor has to be called. The only way around it I see is containment. Have the class inside or referencing the other class.
I don't believe you can get around calling the constructor. But you could do something like this:
public class BaseClass : SomeOtherBase
{
public BaseClass() {}
protected virtual void Setup()
{
}
}
public BaseClassProxy : BaseClass
{
bool _fakeOut;
protected BaseClassProxy(bool fakeOut)
{
_fakeOut = fakeOut;
Setup();
}
public override void Setup()
{
if(_fakeOut)
{
base.Setup();
}
//Your other constructor code
}
}
If what you want is to not call either of the two base class constructors, this cannot be done.
C# class constructors must call base class constructors. If you don't call one explicitly, base( ) is implied. In your example, if you do not specify which base class constructor to call, it is the same as:
public BaseClassProxy : BaseClass
{
public BaseClassProxy() : base() { }
}
If you prefer to use the other base class constructor, you can use:
public BaseClassProxy : BaseClass
{
public BaseClassProxy() : base(someIntValue) { }
}
Either way, one of the two will be called, explicitly or implicitly.
When you create a BaseClassProxy object it NEEDS to create a instance of it's base class, so you need to call the base class constructor, what you can doo is choose wich one to call, like:
public BaseClassProxy (bool fakeOut) : base (10) {}
To call the second constructor instead of the first one
I am affraid that not base calling constructor isn't option.
I ended up doing something like this:
public class BaseClassProxy : BaseClass
{
public BaseClass BaseClass { get; private set; }
public virtual int MethodINeedToOverride(){}
public virtual string PropertyINeedToOverride() { get; protected set; }
}
This got me around some of the bad practices of the base class.
constructors are public by nature. do not use a constructor and use another for construction and make it private.so you would create an instance with no paramtersand call that function for constructing your object instance.
All right, here is an ugly solution to the problem of one class inheriting the constructors of another class that I didn't want to allow some of them to work. I was hoping to avoid using this in my class but here it is:
Here is my class constructor:
public MyClass();
{
throw new Exception("Error: Must call constructor with parameters.");
}
OK now you were warned that it was ugly. No complaints please!
I wanted to force at least the minimal parameters from my main constructor without it allowing the inherited base constructor with no parameters.
I also believe that if you create a constructor and do not put the : base() after it that it will not call the base class constructor. And if you create constructors for all of the ones in the base class and provide the same exact parameters for them in the main class, that it will not pass through. But this can be tedious if you have a lot of constructors in the base class!
It is possible to create an object without calling the parameterless constructor (see answer above). But I use code like this to create a base class and an inherited class, in which I can choose whether to execute the base class's init.
public class MyClass_Base
{
public MyClass_Base()
{
/// Don't call the InitClass() when the object is inherited
/// !!! CAUTION: The inherited constructor must call InitClass() itself when init is needed !!!
if (this.GetType().IsSubclassOf(typeof(MyClass_Base)) == false)
{
this.InitClass();
}
}
protected void InitClass()
{
// The init stuff
}
}
public class MyClass : MyClass_Base
{
public MyClass(bool callBaseClassInit)
{
if(callBaseClassInit == true)
base.InitClass();
}
}
Here is my solution to the problem
using System;
public class Program
{
public static void Main()
{
Console.WriteLine(new Child().Test);
}
public class Child : Parent {
public Child() : base(false) {
//No Parent Constructor called
}
}
public class Parent {
public int Test {get;set;}
public Parent()
{
Test = 5;
}
public Parent(bool NoBase){
//Don't do anything
}
}
}
A simple elegant solution. You can change it according to your need.
Another simple solution from me:
class parent
{
public parent()
{
//code for all children
if (this.GetType() == typeof(child1))
{
//code only for objects of class "child1"
}
else
{
//code for objects of other child classes
}
}
}
class child1 : parent
{
public child1()
{}
}
// class child2: parent ... child3 : parent ... e.t.c