Extension method and Explicit casting

Artur Keyan picture Artur Keyan · Nov 29, 2011 · Viewed 11.1k times · Source

I'm using class from some assembly(source code is not available), so it is not possible to change their's code I need to add extension method for explicit cast operator, is there any way to achieve that? (I have tried to add as regular extension method, but without success)

 public static explicit operator MembershipUser(this MembershipUser membership, User user)
    {
        return new MembershipUser("SimplyMembershipProvider", user.UserName, user.UserId, user.Email, null, null, user.IsApproved, user.IsLocked,
            user.CreateDate, user.LastLoginDate, user.LastActivityDate, user.CreateDate, DateTime.MinValue);
    }

how can i solve this?

Answer

Christopher Currens picture Christopher Currens · Nov 29, 2011

You cannot overload operators via Extension methods.

Best you can do with an extension method:

public static MembershipUser ConvertToMembershipUser(this User user)
{
    return new MembershipUser("SimplyMembershipProvider", 
                              user.UserName, 
                              user.UserId, 
                              user.Email, 
                              null, 
                              null, 
                              user.IsApproved, 
                              user.IsLocked,
                              user.CreateDate, 
                              user.LastLoginDate, 
                              user.LastActivityDate,
                              user.CreateDate, 
                              DateTime.MinValue);
}

MembershipUser membershipUser = aUser.ConvertToMembershipUser();