I have inherited property in my children class. But when I am trying to call parent method, it always using it's own (parent) property. How I can explain c# to use inherited property?
class ParentClass
{
protected int autoinc;
public ParentClass()
{
autoinc = 1000;
}
public Show()
{
Debug.Log("AutoInc = " + autoinc);
}
}
class ChildClass : ParentClass
{
protected int autoinc;
public ChildClass()
{
autoinc = 2000;
}
}
/* Calling code */
ChildClass cc = new ChildClass();
cc.Show();
// I need above code to show 2000, but it shown 1000.
Sorry, this is definitely stupid question. But I need your help anyway.
autoinc field in child class hides declaration of field with same name in parent class. Just remove that field from child class:
class ChildClass : ParentClass
{
public ChildClass()
{
autoinc = 2000;
}
}
Remember, when you use inheritance, then Child object is Parent object. You don't need to define parent fields or other members in child object, because they all are already here. Unless you want to hide or override some member of parent class.
Related
I have an inner class to contain methods of my project; and I want to use the Form class event handlers to call my methods from the inner class; but I am having trouble accessing members of the outer class such as label1, label2, label3 etc.
How do I access a field of an outer class?
I'm trying to make an association inside the constructor :
public partial class Form1 : Form
{
// declare inner class here
public MachineClass machineObj = new MachineClass();
public class MachineClass
{
int fruit1, fruit2, fruit3, fruitvalue1, fruitvalue2, fruitvalue3;
public void spinslot()
{
Random player = new Random();
fruit1 = player.Next(10);//generates a number between 0 and 9
fruit2 = player.Next(10);//generates a number between 0 and 9
fruit3 = player.Next(10);//generates a number between 0 and 9
fruitvalue1 = fruit1 + 1;//
fruitvalue2 = fruit2 + 1;//
fruitvalue3 = fruit3 + 1;//
label1.ImageIndex = fruit1;//display image in label - uses image list
label2.ImageIndex = fruit2;//display image in label - uses image list
label3.ImageIndex = fruit3;//display image in label - uses image list
}
}
}
One way, off the top of my head, to do this, would be for the parent class to keep reference to the child, and vice versa. So for this class structure:
class ParentClass
{
public ParentClass()
{
this.child = new ChildClass(this);
}
public ChildClass child { get; set; }
class ChildClass
{
public ParentClass Parent { get; set; }
public ChildClass(ParentClass par)
{
this.Parent = parent;
}
}
}
then any time you wanted to access a field in the parent class from the subclass, you could just call .Parent.Whatever. Granted, this forces you to instantiate both at the same time, so I'm not sure if it's that great a way of accomplishing what you intend, nor whether it'll work for your purposes.
Edit: Alternately, you could use ParentClass as a factory of sorts for ChildClass, like so:
class ParentClass
{
public ParentClass() { }
public class ChildClass
{
public ParentClass Parent { get; set; }
public ChildClass(ParentClass par)
{
this.Parent = par;
}
}
public ChildClass GetChild()
{
return new ChildClass(this);
}
}
and you could instantiate an unlimited number of related ChildClasses from any given ParentClass, and calling .Parent from any ChildClass would refer to the ParentClass from which it was created.
I'd like to make a note, though, that in my experience I've found very few uses for inner classes, and I can't think of a single time where the above class designs would have benefited me. Particularly given that your example doesn't really seem like it's doing anything special, it seems like you'd be better off constructing a normal class outside the scope of your Form class and passing data to it as needed, rather than trying to create a convoluted inner class with a parent/child relation.
Here is what you really need to do to make this work and to do so with a better OO design.
First-up, define the internal MachineClass like this:
public class MachineClass
{
private int fruit1, fruit2, fruit3;
public delegate void FruitUpdate(int value);
public event FruitUpdate FruitUpdate1;
public event FruitUpdate FruitUpdate2;
public event FruitUpdate FruitUpdate3;
public void spinslot()
{
Random player = new Random();
fruit1 = player.Next(10);
fruit2 = player.Next(10);
fruit3 = player.Next(10);
if (this.FruitUpdate1 != null) this.FruitUpdate1(fruit1);
if (this.FruitUpdate2 != null) this.FruitUpdate2(fruit2);
if (this.FruitUpdate3 != null) this.FruitUpdate3(fruit3);
}
}
The FruitUpdate delegate allows the definition of three events that can let external users of this class know when updates to the fruit values occur. When updates to the fruit values occur we check that there are handlers attached to the event and then just call the events. The MachineClass does not need to know that there is anything listening.
Now the Form1 class looks a bit like this:
public partial class Form1
{
public MachineClass machineObj = new MachineClass();
public void Form1_Load()
{
this.machineObj.FruitUpdate1 += v => label1.ImageIndex = v;
this.machineObj.FruitUpdate2 += v => label2.ImageIndex = v;
this.machineObj.FruitUpdate3 += v => label3.ImageIndex = v;
}
public class MachineClass
{
/* definition from above */
}
}
Here the Form1 class creates the instance of MachineClass and then attaches handlers to each of the fruit update events. This allows the labels to be updated without the MachineClass being aware of them at all!
I am not getting the base class member in this code. Please suggest. I'm a rookie here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CaseStudy1
{
class base1
{
protected string name = "";
public base1() {}
public base1(string dad)
{
this.name = dad;
}
}
class child1 : base1
{
private string name = "";
public child1()
{
this.name = base.name;
}
public void show()
{
base1 b1 = new base1("Daddy");
Console.WriteLine("base name"+base.name);
Console.WriteLine("child's name" + name);
}
public static void Main(string[] args)
{
child1 c1 = new child1();
c1.show();
Console.ReadLine();
}
}
In C# Inheritance, what you have as a "child" class is not really a child (being owned by the base) but a more specific version of the base (as like a football being a specific kind of ball). The base class and the inherited class are the same actual object. Therefore, the new keyword is out of place, since what you want is the base class's name, not a new base object all together. By using the same name for a property in both the base and the inherited class, you are "hiding" the property in the base, since a single object can't have the same property twice (in your example, your object can't have 2 different name. If what you want to do is have the inherited class know the name of the base, they need to be different properties.
The best way to think of it is that if you use new to create an object, that object will have every property and method of itself and any class above it in the class tree, so a child1 object would have the child1 and the base1 properties and methods, but a new base1 object only has the base1 properties and methods.
As a side effect, a child1 object can be used in any statement that requires a base1 object, since a child1 object is a base1 object.
Here within the Show method you create the new instance of base1 class.So you cannot read from setted value from using base.name.because of b1 is new instance.
You can use as follows.
class base1
{
protected string name { get; set; }
public base1() { }
}
class child1 : base1
{
private string name = "";
public void show()
{
base.name = "Daddy";
this.name = base.name;
Console.WriteLine("base name" + base.name);
Console.WriteLine("child's name" + name);
}
}
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.
Let's say I have a class which has a property hiding it's base property and a nested class inside this class. Is it possible to access the base hidden *virtual* property from the nested class?
Here is an example:
class BaseClass
{
protected virtual String SomeProperty {get; set;}
}
class Inherited : BaseClass
{
protected new String SomeProperty {get; set;}
class Nested
{
Inherited parent;
public Nested(Inherited parent)
{
this.parent = parent;
}
public void SomeMethod()
{
//How do I access the SomeProperty which belongs to the BaseClass?
}
}
}
The only solution that I can think of is to add a private method to Inherited class which returns base.SomeProperty Is there a better solution?
You could cast your InheritedClass reference to BaseClass. Since you hide the base property instead of overriding it, this should do the trick.
public void SomeMethod()
{
BaseClass baseRef = parent;
// do stuff with the base property:
baseRef.SomeProperty = someValue;
}
Edit:
To make this work, the SomeProperty property of the BaseClass has to be accessible to the nested class, either by making it internal (if you don't want to make the property accessible outside the declaring assembly) or protected internal (if you want to allow overriding in derived classes from other assemblies).
If both options are off limits (ie. when your derived class already is in another assembly), you won't get around declaring a wrapper property.
private string SomeBaseProperty
{
get
{
return base.SomeProperty;
}
set
{
base.SomeProperty = value;
}
}
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());
}
}