using System; using System.Reflection; class Program { // // Inheritance diagram // // CAR ----- MUSICAR ---- NICECAR // \ \ // \ +------ OLDCAR // \ // +---- HOMEMADECAR // base class public abstract class Car { public string nickname; public string color; public int miles; } // class for a car that might have a stereo public abstract class musiCar : Car { public bool hasStereo; } // inherited class public class niceCar : musiCar { public bool hasMP314Player; } // inherited class public class oldCar : musiCar { public int age; } // car that is only related to the base class car public class homeMadeCar : Car { public bool hasStereo; public bool isEpa; } public static void displayCar(Car myCar) { Console.WriteLine("The {0} car...", myCar.color); Console.WriteLine(" - is called '{0}'", myCar.nickname); Console.WriteLine(" - has run for '{0}' miles", myCar.miles); // is it a musicar? if (myCar is musiCar) { if (((musiCar)myCar).hasStereo) Console.WriteLine(" - has a stereo"); else Console.WriteLine(" - has no stereo"); // is it an old car? if (myCar is oldCar) { Console.WriteLine(" - is {0} years old", ((oldCar)myCar).age); } // is it a nice car? if (myCar is niceCar) { if (((niceCar)myCar).hasMP314Player) Console.WriteLine(" - has an MP314 player"); else Console.WriteLine(" - has no MP314 player"); } } // is it an epatraktor? ( http://www.epatraktor.se/galleri/5337.jpg ) if (myCar is homeMadeCar) { if (((homeMadeCar)myCar).isEpa) Console.WriteLine(" - this is in fact an epatraktor."); else Console.WriteLine(" - thank System.Math.Random.God() - it is not an epatraktor"); } // what if it is some other class that also might have a stereo if (!(myCar is musiCar)) { try { Type T = myCar.GetType(); FieldInfo field = T.GetField("hasStereo"); if ((bool)field.GetValue(myCar)) Console.WriteLine(" - has a stereo :)"); else Console.WriteLine(" - has no stereo :)"); } catch (Exception ex) { Console.WriteLine(" the 'hasStereo' of this car was not a bool..."); Console.WriteLine(" {0}", ex.Message); } } } static void Main(string[] args) { oldCar c1 = new oldCar(); c1.age = 25; c1.color = "beige"; c1.hasStereo = false; c1.miles = int.MaxValue / 2; c1.nickname = "ugly betty"; niceCar c2 = new niceCar(); c2.color = "light blue metallic"; c2.hasMP314Player = true; c2.hasStereo = c2.hasMP314Player; c2.miles = 1337; c2.nickname = "Turing the Tempest"; homeMadeCar c3 = new homeMadeCar(); c3.color = "black"; c3.hasStereo = true; c3.isEpa = true; c3.miles = 555; c3.nickname = "KB::P_WAGON"; Console.WriteLine(); Console.WriteLine("CAR 1"); displayCar(c1); Console.WriteLine(); Console.WriteLine("CAR 2"); displayCar(c2); Console.WriteLine(); Console.WriteLine("\"CAR\" 3"); displayCar(c3); } }