The text of this article is not in this database — only its details are. Read it on the old site: Downcasting in C#
3 Comments
Join the conversation! Your thoughts help the community grow.
Sign in to leave a comment.
The text of this article is not in this database — only its details are. Read it on the old site: Downcasting in C#
Join the conversation! Your thoughts help the community grow.
Sign in to leave a comment.
JarrodPosted Feb 18, 2011, 4:37 PM
But don't propagate bad code. Place a virtual Save() method on the Base Person class and have your Lawyer class override it to add its additional properties. public class Person { public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public int Age { get; set; } public virtual void Save() { Console.WriteLine("Name: " + mFirstName + " " + mMiddleName + " " + mLastName); Console.WriteLine("Age: " + mAge.ToString()); } } public class Lawyer : Person { public int NumberOfPeopleShafted { get; set; } public int NumberOfLiesTold { get; set; } public override void Save() { base.Save(); Console.WriteLine("Number of Clients Shafted: " + NumberOfPeopleShafted); Console.WriteLine("Number of Lies Told: " + NumberOfLiesTold); } } // Then you don't even need the PersonHandler class but just for grins: public static void SavePerson<T>(T pers) where T : Person { Type tPers = pers.GetType(); string[] arr = tPers.ToString().Split('.'); string personType = arr[arr.Length - 1]; switch (personType) { case "Person": Console.WriteLine("Save Type: " + personType); T.Save(); break; case "Lawyer": Console.WriteLine("Save Type: " + personType); T.Save(); } } Also, for dowcasting, don't do an explicit cast... use dynamic casting: Lawyer myLawyer = (MyPersonReference as Lawyer); if the cast fails then the myLawyer reference will be null.
Peter RitchiePosted Mar 2, 2009, 4:07 PM
Polymorphism is the object-oriented method of doing this. You should have one method per case. You've got this use issue that the textual name you're comparing against is decoupled from the type name. If you changed the name of your type then you'd have runtime errors. Using polymorphism gets you compile-time checking. Not to mention, what method that gets called is decided upon compilation and no string comparison would be needed.