Sam Arnold Sam Arnold - 13 days ago 6
C# Question

C# explaining New and Base and Derived Classes. Inheritance explained in detail

I created an array of a parent class and assigned it to the base class and thought the name would be carried over in inheritance but it is not. Why is that? Why doesn't assignment operator work setting child to the parent's array? I looked in the C# library and it talks about using New and Base but I am not sure how it works or why it works that way?

It is meant to be pseudo code. Not meant to be run. Just for conceptually why. Why is the assignment of Derived class to Parents class bad.

public class Person
{
// Parent Class
public int Name = "Person";
}

public class ShopOwner : Person
{
// Child class
public int Name = "Ted the Shop Owner";
}

static void Main(string[] args)
{
// Create Derived Class and Array of the parent
ShopOwner ShopKeeper = new ShopOwner ();
public Person[] MyPeople = new Person[50];

// set a single location in the array to derived.
MyPeople[0] = ShopKeeper;

// Print the results of Shop keeper
Console.WriteLine(ShopKeeper.Name);
// should be and is Ted

Console.WriteLine(MyPeople[0].Name);
// Thought it would be ted but it isnt? whhhyy is that?
// when I assigned them to the parent to be array = 2 child


}

Answer

Here's my best guess as to what Sam Arnold is trying to accomplish. He is asking why the second Console.WriteLine() was not outputting "Ted the Shop Owner." The missing piece I think he was asking about was casting MyPeople[0] to a ShopOwner since myPeople is an array of Person. Explicitly marking ShopOwner.Name as new helps to clarify intent.

void Main()
{
    // Create Derived Class and Array of the parent
   var shopKeeper = new ShopOwner();
   var myPeople = new Person[50];

   // set a single location in the array to derived. 
   myPeople[0] = shopKeeper;

   // Print the results of Shop keeper 
   Console.WriteLine(shopKeeper.Name);
   // should be and is Ted 

   Console.WriteLine(((ShopOwner)myPeople[0]).Name);
    // Thought it would be ted but it isnt? whhhyy is that? 
    // when I assigned them to the parent to be array  = 2 child
}

// Define other methods and classes here
public class Person
{
  // Parent Class
   public string Name = "Person";
} 

public class ShopOwner : Person
{
   // Child class 
   public new string Name = "Ted the Shop Owner";
} 

// Output
// -----------------------------
// Ted the Shop Owner
// Ted the Shop Owner
Comments