Search code examples
c#sharepointweb-parts

Error Regarding User Defined Conversion


I have the following operator in my Visual WebPart's codebehind file:

public static implicit operator TemplateControl
(ScholarChip.PaymentProcessor.PaymentProcessor.PaymentProcessor target)
    {
        return ((target == null) ? null : target.TemplateControl);
    }

I'm receiving the error:

User-defined conversion must convert to or from the enclosing type  

I'm unfamiliar with the above error. Can anyone suggest how I might rectify it? The code is being used in a Sharepoint 2010 Visual WebPart.

Thanks much:)


Solution

  • The problem is that you're defining a conversion between PaymentProcessor and TemplateControl, but you're not defining that conversion in either the PaymentProcessor class or the TemplateControl class. TemplateClass seems like it's part of a framework, so I doubt you can define the conversion in that class.

    A user-defined conversion must be a member of one of the two types being converted (which is just another way of saying what the error message says). In other words, if you control the PaymentProcessor class, move the conversion into that class. If you control neither class, you're out of luck, and you need to handle the conversion in a normal method.

    As an example, this will give the same compiler error you saw:

    class A {}
    class B {}
    class C
    {
        public static implicit operator A(B source) { return new A(); }
    }
    

    This will compile:

    class A {}
    class B
    {
        public static implicit operator A(B source) { return new A(); }
    }
    

    So will this:

    class A
    {
        public static implicit operator A(B source) { return new A(); }
    }
    class B {}