Extension method and Explicit casting

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();

As others have said, you can't overload operators using extension methods - but a simple extension method would still be useful:

public static MembershipUser ToMembershipUser(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);
}

Then just use it as:

User user = ...;
MembershipUser membershipUser = user.ToMembershipUser();

Personally I find this clearer than using an explicit conversion anyway - I very rarely go in for operator overloading. In particular, given that the classes certainly sound related, a naive user might expect this code:

User user = ...;
MembershipUser membershipUser = (MembershipUser) user;

... to be a normal reference conversion, expecting MembershipUser to be a class derived from User. This is important in terms of object identity - if that were the case, it wouldn't be changing the object involved (and changes to the object referred to by user would still be visible via membershipUser).

Creating a ToMembershipUser method makes it clearer that you're converting from one form to a new object of the other type. All IMO, of course :)


No, you cannot add an extension conversion.

Explicit or implicit conversions may only be defined if you control the source code for one of the types involved. In your case, you can control either MembershipUser or User, you do not need to control both. But you must control one.

If you control neither, you'll simply need to define the conversion in a method of some other class whose job it is to control such a conversion.

class UserConverter 
{
    public MembershipUser ConvertFrom(User user) 
    {
        return ...
    }
}

Not saying this is a good practice (read other answers for why you should not want this, but if the classes are not sealed, this is possible, just not using extension methods).

Basically, you can create a surrogate class inheriting User who defines the casting operator, something like:

    class UserSurrogate : User
    {
        public static explicit operator UserSurrogate(MemberShipUser other)
        {
            return  new UserSurrogate() { Name = other.Name };
        }
    }

    class User
    {
        public string Name { get; set; }
    }

    class MemberShipUser
    {
        public string Name { get; set; }   
    }

Comments

  1. Maddox

    • 2020/10/27

    You cannot overload operators via Extension methods. Best you can do with an extension method:

  2. Sylas

    • 2015/4/28

    Extension method and Explicit casting. Ask Question Asked 9 years, 9 months ago. Active 9 years, 9 months ago. Viewed 11k times 9 1. I'm using class from some

  3. Thiago

    • 2017/4/17

    One problem is that the extension method causes an implicit cast to object before doing the cast to the target type, so it bypasses all the 

  4. Davion

    • 2018/5/4

    Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type. For client code written in C#, F# and Visual Basic, there's no apparent

  5. Dupont

    • 2021/7/16

    I'm writing a C# extension-method that converts any object to a type. E.g. the method shall convert a string with value "y" to a true -boolean - so there will 

  6. Barrett

    • 2020/2/17

    Extension methods really are just syntactic sugar to call static methods in a nicer way. The extension method is not part of BigObject , it's a completely separate static method. It's actually a pretty good use of extension methods, and very handy for DTO conversions in particular.

  7. Braden

    • 2017/5/10

    C# won't implicitly cast an object to another type unless there is a clue about the target type. Assume the following: class A { public static implicit operator 

  8. Amos

    • 2015/10/2

    3] Explicit cast does not guarantee that the extension method will be visible. 4] Code behind using statements is different from page designer import directive. And i will do the following in response to those questions : 1] Namespace on the designer should be added like this : <%@ Import Namespace="WebSite2.Extension" %>.

  9. Zayden

    • 2019/11/5

    public static class Extensions { public static explicit operator ViewModel(Model but an extension implicit cast would solve this issue for my purposes.

  10. Joel

    • 2021/5/11

    Even for dealing with those legacy collections, using the Cast or OfType extension methods (depending on the desired semantics) may be better, as it makes crystal clear what you are actually doing. It’s a good idea never to hide a cast behind a somewhat obscure language feature, even more so a feature a lot of people misinterpret at first.

  11. Carbone

    • 2016/3/2

    public class A { public static explicit operator B(A a) { return new B(); } extension method is that you gain a fluent interface for explicit casting (if 

  12. Scott

    • 2016/12/16

    Basic knowledge of programming in C# and creating extension methods is assumed. Converting from one data type to another is quite commonplace in computer programming. In C# this can be done in various ways: Implicit Casting; Explicit Casting; Using System.Convert; The list above will be described in the following three sections. Implicit Casting

  13. Melvin

    • 2018/11/3

    Consider casting the dynamic arguments or calling the extension method without the cast dynamic to string if the compiled data type supports it

  14. Kristian

    • 2019/3/29

    A cast is a way of explicitly informing the compiler that you intend to make the conversion and that you are aware that data loss might occur, or the cast may fail at runtime. To perform a cast, specify the type that you are casting to in parentheses in front of the value or variable to be converted. The following program casts a double to an

  15. Nico

    • 2018/6/4

    Cast. The Cast method casts every element. It is an extension in the System.Linq namespace. It casts each element to the specified type.

  16. Daniel

    • 2020/3/7

    When calling extension methods, that additional type is implicit. This is easy with static typing: IFoo f = new Foo(); // Implicit cast to interface f.

Comments are closed.

Recent Posts