Reputation: 33
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();
}
}
Upvotes: 0
Views: 130
Reputation: 22323
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.
Upvotes: 2
Reputation: 5804
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);
}
}
Upvotes: 0