We help IT Professionals succeed at work.
Get Started

Inheritance problem - unable to cast object of type...

supernova58 asked
Last Modified: 2008-02-26
I have three classes , user, admin and teacher,where admin and teacher inherit from user class. All of the have the same properties, except that in admin I set a property named role to enum.admin and in teacher I set that property to enum.teacher. I have two questions here.

First when I try to cast an object of type user to admin, I receive "unable to cast object of type User to type Admin" error. I don't know why I receive this error, while all the properties in user class and admin are all the same also it's the same for teacher.

My second question is that,in my web application, I want to authenticate the user and return and object of the user class when the authentication is successful. In the web page(code behind) , I check the role property of that user object,if it is teacher i want to cast it to teacher class and if it is admin cast it to admin.(which fails as in my first question). I was wondering whether i am making a good design and solution for this purpose (having multiple types of users) by having a general user class and two inherited teacher and admin class. Or maybe there could be better and more object-oriented solutions than this ? Any suggestions?

Watch Question
This problem has been solved!
Unlock 1 Answer and 2 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE