Mažas
Mažas

Reputation: 397

c# access child class from parent

I have two classes. Jewellery is base and Ring inherits from it.

class Jewellery 
{
     public string Name { get; set; }
     ......

     public Jewellery(string name) 
     {
          Name = name;
     }
}

.

class Ring : Jewellery
{
     public string Size { get; set; }

     public Ring(string name, string size) :base(name)
     {
          Size = size
     }
}

Now in main i created List of Jewellery and in that list i added Ring object.

Ring ring = new Ring("Diamond", "Very big");
List<Jewellery> jewellery = new List<Jewellery>();
jewellery.Add(ring);

Now when debugging i can access ring object from jewellery list. Can i do it from code? I think this should be done like this, but this doesn't work.

jewellery[0].Ring

Upvotes: 1

Views: 2161

Answers (1)

NikolaiDante
NikolaiDante

Reputation: 18649

You need to cast it, e.g.:

var myRing = (Ring)jewellery[0];

or

var maybeRing = jewellery[0] as Ring;
if (maybeRing != null)
{
 // do stuff
}

or

if (jewellery[0] is Ring)
{
   // Cast and do stuff
}

For multiple types you can

if (jewellery[0] is Ring)
{
   // Cast and do stuff
}
else if(jewllery[0] is Necklace)
{
  // and so on
}

See MSDN on safe casting.


Depending on what you want to do you can use Linq to filter by type:

Given:

List<Jewellery> things = new List<Jewllery>();

Then:

public IList<T> GetJewellery<T>(this jewellery) where T : Jewellery
{
    return jewellery.OfType<T>().ToList();
}

Can:

IList<Necklace> necklaces = things.GetJewellery<Necklace>();
IList<Ring> rings = things.GetJewellery<Ring>();

Upvotes: 4

Related Questions