Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to case a base class into a derived class

Status
Not open for further replies.
Jul 8, 2007
1
US
Can anyone tell me how to case a base class into a derived class like in the example below. Here I am receiving an exception when the person object is cast as an employee.
Code:
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            p.firstName = "egar";
            Employee e = (Employee)p;
        }
    }
    public class Employee : Person
    {
        private string _dept;

        public Employee()
        {
            _dept = "";
        }
        public string dept
        {
            get
            {
                return _dept;
            }
            set
            {
                _dept = value;
            }
        }
    }
    public class Person
    {
        private string _firstName;

        public Person()
        {
            _firstName = "";
        }
        public string firstName
        {
            get
            {
                return _firstName;
            }
            set
            {
                _firstName = value;
            }
        }
    }
}
 
Person p = new Person();
p.firstName = "egar";
Employee e = (Employee)p;

Employee is a type of Person - a Person is NOT a type of employee. So it should read

Person p = new Employee();
//at this point p will only show methods and properties avaiable from the Person class unless you cast to employee
p.firstName = "egar";
Employee e = (Employee)p;

Not that casting is slow and will drastically reduce performance if used a lot. Instead, ask yourself why you need to cast it to an employee. If you still decide that you HAVE to cast it to that type, then try to limit the number of times you do the cast.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top