Casting

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

I have created a class that inherits MembershipUser:
public class UserHelper : MembershipUser {
....

Then I am creating a user as follows:
UserHelper user = (UserHelper)Membership.CreateUser("me", "pass",
"(e-mail address removed)", null, null, true, null, out status);

Membership.CreateUser returns a MembershipUser

But I get an error:
Unable to cast object of type 'System.Web.Security.MembershipUser' to
type 'MyApp.Security.Membership.UserHelper'.

If I don't cast it, which means, using:
UserHelper user = Membership.CreateUser("me", "pass", "(e-mail address removed)",
null, null, true, null, out status);

It does not compile and I get the error:
Cannot implicitly convert type 'System.Web.Security.MembershipUser' to
'MyApp.Security.Membership.UserHelper'. An explicit conversion exists
(are you missing a cast?)

What am I doing wrong?

Thanks,
Miguel
 
shapper said:
I have created a class that inherits MembershipUser:
public class UserHelper : MembershipUser {
...

Then I am creating a user as follows:
UserHelper user = (UserHelper)Membership.CreateUser("me", "pass",
"(e-mail address removed)", null, null, true, null, out status);

Membership.CreateUser returns a MembershipUser

But I get an error:
Unable to cast object of type 'System.Web.Security.MembershipUser' to
type 'MyApp.Security.Membership.UserHelper'.

If I don't cast it, which means, using:
UserHelper user = Membership.CreateUser("me", "pass", "(e-mail address removed)",
null, null, true, null, out status);

It does not compile and I get the error:
Cannot implicitly convert type 'System.Web.Security.MembershipUser' to
'MyApp.Security.Membership.UserHelper'. An explicit conversion exists
(are you missing a cast?)

What am I doing wrong?

You're casting in the wrong direction. If you have a UserHelper, you can
cast it to a MembershipUser, but you cannot safely start with a base object
and cast it to a derived class. What would happen to any additional
members you might have added? They wouldn't be present in the
MembershipUser instance.

In this case, you will have to use composition instead of inheritance. Add
a MembershipUser instance to UserHelper ad a member, call CreateUser, and
pass the MembershipUser object you get to the constructor for UserHelper.
 
Back
Top