parent class's constructer in a child class in C# - c#

I have one parent class and one child class.
The parent has a constructor that initializes its parameters.
My question is: How does the child look to the parent's constructor? Can I define a constructor for the children?

you can use base(...) in ctor of your child class.
foreacmple:
public class Child : BaseClass
{
public Child() : base(/*some parameters*/) //CALLING BaseClass parametrized ctor
{
}
}
Just note, if you don't need some specific parameters, just do not do anything, cause BaseClass default ctor will be called by the way when you call ctor of a Child class.

This inheritance sample shows:
how to call the parent constructor from a new constructor on the child
how to pass parameters required by the parent constructor
Code sample:
public class Parent
{
private object _member;
public Parent(object member)
{
this._member = member;
}
}
public class Child : Parent
{
public Child(object member)
: base(member)
{
}
}

You have to define constructors for the children. You can call the base class' constructor using : base() between the constructor prototype and its implementation:
public class Parent {
public Parent() {
...
}
}
public class Child : Parent {
public Child() : base() { // calls Parent.ctor
}
}

Of course.
You are after the "base" keyword.
public class Fruit
{
string TypeOfFruit { get; set; }
public Fruit (string typeOfFruit)
{
TypeOfFruit = typeOfFruit;
}
}
public class Apple : Fruit
{
string AppleType { get; set; }
public Apple(string appleType) : base("Apple")
{
AppleType = appleType;
}
}

You can very well define a constructor for the child class the default one is provided only in case when you do not define a constructor for a class
Meanwhile for how to look up for the constructor of parent
It would check for a parameterless constructor to be present in the parent class and in case you do not have one ( well the compiler lets you know the same) or else you will have to call the parent constructor with the parameters like base("This is the string parameter")
If you meant something else please update the question.

Related

Constructor in C#

I have a parent class with 2 constructor and the derived class trying to call the constructor of parent in 2 different methods
public class Parent
{
public Parent()
{
//some stuffs
}
public Parent(string st)
{
//some stuffs
}
}
Now I have a derived class with two methods.
I Have to use Parent-constructor in one method and the Parent(string st) in other method.
But here It is always calling the Parent-constructor. Below is the derived class
public class Derived : Parent
{
public void GetData()
{
//Here I initialize the constructor like this
Parent p = new Parent();
}
public void GetData1()
{
string s = "1";
Parent p = new Parent(s);
}
}
Please let me how to make this happen.
Thanks in advance.
Just have two constructors in your Derived class that use the appropriate constructor in the base.
public class Derived : Parent
{
public Derived() : base()
{
}
public Derived(string s) : base(s)
{
}
}
The :base() nomenclature will invoke the parent constructor.
Use the parent constructor call "base"
public class Parent {
public Parent() {}
public Parent(string s) {}
}
public class Child : Parents {
public Child():base() // Call Parent empty constructor
public Child(string s): base(s) // Call Parent Constructor with parameter
}
Your error comes because you're instanciate a new Object Parents in your Child.
With Base(), you call the parent constructor without instanciate him.
Calling new Derived() will call the Parent() ctor because it inherits from Parent and has an implicit Derived() : base().
After you have constructed Derived() calling the method (not constructor) GetData1() will call the Parent(string st) constructor
These are completely separate routes of constructing parent and it seem you are confusing them
The Parent() constructor is always called because you Derived derives from Parent but doesnt include a constructor, hence a default constructor is created, which calls the parameterless parent constructor.
The call to Parent p = new Parent(s); will call the constructor of Parent that takes a parameter.
If you want to call the parent constructor when creating a Derived object, you have to chain the constructors using base().
public class Derived : Parent
{
public void Derived()
: base()
{
//code
}
public void Derived(string s)
:base(s)
{
//code
}
}

What is the difference between simple constructor and constructor with base?

I have some doubts in my below codes,
public class ClassA: BaseClass
{
public ClassA(UIElement element)
: base(element)
{
}
}
public class ClassA: BaseClass
{
public ClassA(UIElement element)
{
}
}
What is the difference between the above codes?
Doubts:
1.It is necessary to call base constructor
2.What is the use to Call the base constructor
3.If we didn't call base constructor it calls implicitly.
Any one please provide suggestion for this.
the first one instructs to use the BaseClass(UIElement) constructor, while the other one will use BaseClass() to be initialised instead.
To your questions; it all depends on if it makes sense to initiase BaseClass with the passed element or not.
Not always, if you don't specify anything then base() will be called
base() as you already did
Yes
In each case a base constructor is called, just implicitly and using the default in the latter case - in the first case it's using an explicit base constructor which accepts an argument. If no default parameterless constructor existed on the base class then an error would be encountered if it wasn't explicitly called by the user in order to provide the required input.
So, it's only necessary to call if you need to pass input to a specific constructor or a default public constructor is not defined.
1-3. no it's not necessary it call it automagically if the base calss contain a constructor without parameter
2. you use base when you inherit from another class, the part you inherited need to be constructed too so you have to call the base constructor
Please note 2 more things using chained contructors
The Base Contructor is always called before the actual constructor.
The constructors can have different accessabilities like private or public. You cannot chain every constructor from the base to the derived class.
The first one passes a parameter to the base constructor, while the second one uses the default (parameterless constructor).
public class Human
{
public string Name { get; set; }
public Human()
{
Name = "No name";
}
public Human(string name)
{
Name = name + " Jr.";
}
}
public class Male : Human
{
public Male() {}
public Male(string name) : base(name) {}
}
public class Female : Human
{
public Female() { Name = "Girl"; }
}
var unnamedHuman = new Human();
//unnamedHuman.Name == "No name"
var namedHuman = new Human("Jon");
//namedHuman.Name == "Jon"
var unnamedMale = new Male();
// unnamedMale.Name == "No name"
var namedMale = new Male("Chris");
// namedMale.Name == "Chris Jr";
var unnamedFemale = new Female()
// unnamedFemale.Name == "Girl"
The logic:
When you initialize a child class (by calling their ctor), first its base class constructors are called in order (top-down), the final one would be your child class' constructor you invoked.
By default, the default parameterless contructor is used but you can specify and pass arguments to the base constructor by using base(parameter1, p2).
If your BaseClass looked like:
public class BaseClass
{
private readonly _element;
public BaseClass(UIElement element)
{
_element = element;
}
}
Then you would absolutely have to call the base constructor, because it's the only constructor that BaseClass has.
If it looked like this:
public class BaseClass
{
private readonly _element;
public BaseClass()
{
_element = default(UIElement);
}
public BaseClass(UIElement element)
{
_element = element;
}
}
Then you would absolutely have to call the base constructor if you wanted to set the element, as it can only be set in the constuctor.
If it looked like this:
public class BaseClass
{
private _element;
public BaseClass()
{
_element = default(UIElement);
}
public BaseClass(UIElement element)
{
_element = element;
}
public UIElement Element
{
get{ return _element; }
set{ _element = value; }
}
}
Then you could choose between:
public class ClassA: BaseClass
{
public ClassA(UIElement element)
: base(element)
{
}
}
public class ClassA: BaseClass
{
public ClassA(UIElement element)
{
Element = element;
}
}
However, the former is clearer and doesn't have a period where Element returns the default (null) during the overall construction.
In all, consider that ClassA is a type of BaseClass. In creating a sensible instance of ClassA you have to do everything entailed in setting up a sensible instance of BaseClass. It is the job of the constructor to make sure this happens. Lean toward calling the base constructor as much as is meaningful.

Generics and Inheritance: How to use the parent in the child class?

I just try to redesign my Silverlight-4 App and tried a bit around with generics.
Simply speaking, I have a tree which can contain 2 types of nodes. As a base class, I created a class that does all the "organization", like having a list of children, a parent, a method to add a child and so on:
public abstract class BaseNode<T> : INotifyPropertyChanged where T: BaseNode<T>
{
protected ObservableCollection<T> _children;
...
}
Second, I add a class that inherits from BaseNode and is the basis for all my treenodes:
public class ServiceNodeBase<T> : BaseNode<ServiceNodeBase<T>> where T : ServiceNodeBase<T>
{
public string Description { get; set; }
...
}
And finally, as I can have two different kinds of nodes, I create a class for each kind, i.e.:
public class ServiceNodeComponent<T> : ServiceNodeBase<ServiceNodeComponent<T>> where T : ServiceNodeComponent<T>
{
public HashSet<Attributes> Attributes { get; set; }
...
}
In the ServiceNodeComponent, I need a method, that scans the tree i.e. to get all the child nodes, that are of the Type ServiceNodeComponent. When parsing the tree, I need to use the parent-type of ServiceNodeComponent (ServiceNodeBase), because the child nodes can also be of the other type.
Now, I do not know how to instantiate the ServiceNodeBase-Variable.
public HashSet<ServiceNodeComponent<T>> GetAllChildComponents()
{
// declaring the container for the found Components is no problem
HashSet<ServiceNodeComponent<T>> resultList = new HashSet<ServiceNodeComponent<T>>();
// but now: how to declare the container for the ServiceBaseNodes?
HashSet<ServiceNodeBase<???>> workingList = new HashSet<ServiceNodeBase<???>>();
Any ideas, how I would implement this?
Thanks in advance,
Frank
The problem is the constraint. It would work if you change it to
public class ServiceNodeComponent<T> : ServiceNodeBase<ServiceNodeComponent<T>>
where T : ServiceNodeBase<T> {
public HashSet<ServiceNodeComponent<T>> GetAllChildComponents() {
// ...
HashSet<ServiceNodeBase<T>> workingList = new HashSet<ServiceNodeBase<T>>();
// ...
}
}

Which constructor will called first in the below example

Which constructor will called first in the below example? When i put break point and execute it first pointed to child constructor but executed the parent class constructor, why this?
could any one please clarify me?
class Program
{
static void Main(string[] args)
{
Child child = new Child();
child.print();
Console.ReadLine();
}
}
public class Parent
{
public Parent()
{
Console.WriteLine("Parent Constructor.");
}
public void print()
{
Console.WriteLine("I'm a Parent Class.");
}
}
public class Child : Parent
{
public Child()
{
Console.WriteLine("Child Constructor.");
}
public new void print()
{
Console.WriteLine("I'm a Child Class.");
}
}
Constructors, when generated from C#, are invoked base-class first, so:
object()
then Parent()
then Child()
Essentially the chained base:.ctor({args}) is prepended to the local .ctor
For this reason you should avoid calling virtual methods during construction, as if Child overrides it, it could fail as Child hasn't initialized the fields defined there yet (they will be zeros).
In C++/CLI you get to choose what order to do things.
Parent is constructed first because it's at the heart of Child.
Child can't be constructed if it's core (Parent) isn't.
Note that the initialization of the class is not limited to executing its constructor. It also initializes its fields.
In the example below, you really want Child's constructor to show that x=3. If not, it would mean that your derived class can't be based on its ancestor behaviour.
public class Parent
{
public int x;
public Parent()
{
x = 3;
}
}
public class Child : Parent
{
public Child()
{
Console.WriteLine("Child Constructor. x="+x.ToString());
}
}

How can I prevent a base constructor from being called by an inheritor in C#?

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

Categories

Resources