C# Array of Objects with Inheritance -


i have problem getting values child class.

class petstore {     public string name;     public int age;      public petstore(string name,int age)     {          this.name=name;          this.age=age;     } }  class dog:petstore {     public string dogtype;      public dog(string name, int age,string dogtype): base(name,age)     {         this.dogtype=dogtype;     } }  class cat:petstore {     public string cattype;      public cat(string name, int age,string cattype): base(name,age)     {         this.cattype=cattype;     } } 

i have code class. need cattype or dogtype array of objects. if did this

petstore[] pets=new petstore[3]; pets[0]=new dog("ben",1,"poodle") pets[1]=new cat("meow,2,"persian") 

how can value of dogtype or cattype using array pets[]? possible? sorry, i'm new this.

welcome stackoverflow, , wonderful world of development in general. unfortunately there lot of problems code stylistic perspective, if don't mind i'll throw in of thoughts along answer actual question.

1) try follow standard style conventions in whatever platform working on. in case of .net, means using pascalcasing when naming classes or methods.

.net style guide

public class petstore {      public void somemethodforthestore() {} } 

2) when doing object-oriented programming, it's important try , model objects after entities of system represent. in case have declared cat , dog subclasses of petstore. way of saying "a dog type of petstore". doesn't make sense. far know, there no dogs house rows , rows of cages animals people walk through , buy pets in.

it more appropriate call superclass pet.

public class dog : pet {} 

3) finally, , believe answer actual question, looking called casting. means taking object may housed in more generic type , trying move more specific type may take advantages of methods , properties may exist on particular subclass. in case dogtype , cattype. requires know instance want cast of particular type want cast to.

// create polymorphic array of pets pet[] pets = new pet[3]; pets[0] = new dog("ben",1,"poodle"); pets[1] = new cat("meow,2,"persian"); 

we know first element of array in case dog, , second cat. because know can cast these instances of pets particular type.

// cast these pets respective types ,  // , access highly specialized behavior! dog dog = (dog) pets[0]; console.writeline(dog.dogtype);  cat cat = (cat) pets[1]; console.writeline(cat.cattype); 

Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -