shashi
shashi

Reputation: 4696

Casting a Parent to a Child object in C#

Lets say I have a parent class User as follows

class User{
  int Id {get;set;}
  UserType Type {get;set;}
  //More properties
}

Then I have two child objects

class Employer : User
{
    // UserType should always be employer
   //some methods and properties
}

class JobSeeker : User
{
    // UserType should always be JobSeeker
   //some methods and properties

}

There are times when I am given an Id and I query the db and load the user. But depending upon whether the user is an employer or job seeker I want to do different things.

The way I do it right now is as follows:

userRepository.TryLoad(userId, out user) 

if (user.UserType == UserType.Employer) 
{
     //do some stuff
}
else if (user.UserType == UserType.JobSeeker) 
{
    // do some other stuff
}

I was wondering if I could do somethings like the following:

userRepository.TryLoad(userId, out user)

 if (user is Seeker) 
{
   //do some other stuff
}
else if (user is Employer) 
{    
   //do some stuff
}

Edit ===

If my userRepository.TryLoad() gives me a user with user.UserType = UserType.Employer, if I use

var employer = user as Employer 

employer is always null.

=== Edit 2====

User defined conversion seems to be a way I could go but then "as" and "is" keywords do not work for User defined conversions

http://msdn.microsoft.com/en-us/library/aa288476(v=vs.71).aspx

http://msdn.microsoft.com/en-us/library/cscsdfbt.aspx

Upvotes: 1

Views: 98

Answers (2)

Tim S.
Tim S.

Reputation: 56536

Assuming TryLoad is actually giving you instances of JobSeeker or Employer, yes, you could do something like this:

userRepository.TryLoad(userId, out user)

if (user is JobSeeker) 
{
   var jobSeeker = (JobSeeker)user;
   //do some other stuff
} // etc

Or as a different style and to avoid checking the type twice, use as instead of is.

userRepository.TryLoad(userId, out user)

var jobSeeker = user as JobSeeker;
if (jobSeeker != null) 
{
   //do some other stuff
} // etc

Upvotes: 0

mattnedrich
mattnedrich

Reputation: 8002

You might want to consider creating a common abstract method on User and have each subclass extend it to perform the specific Seeker/Employer behavior. That way you don't have to worry about what subtype you have.

In general if you need to worry about what type of object you have under the hood (e.g., which child class) this is a design smell, and you should consider refactoring your code.

Upvotes: 1

Related Questions