Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
I have a class public class abcConnection : DbConnection
The class implements all the required members of DbConnection.
I also have an implicit conversion to OdbcConnection:
C++
public static implicit operator System.Data.Odbc.OdbcConnection(abcConnection c)
{
    return c._con;
}

c._con is an underlying private OdbcConnection in the abcConnection class.

When I add the component to a form using the designer in visual studio and assign it to an OdbcCommand I get the following error.
What I've actually done was manually assign the abcConnection as the connecton for the OdbcCommand. This works fine during runtime.

So I guess my question is how can I allow the designer to assign the abcConnection to the OdbcCommand?
C++
Object of type abcConnection cannot be converted to type System.Data.Odbc.OdbcConnection.


Any Ideas?
Posted
Updated 23-Feb-11 8:02am
v4
Comments
Nish Nishant 23-Feb-11 19:56pm    
Interesting question. Voted 5 :-)

1 solution

I don't think that will work since the designer does not really attempt to use implicit (or explicit) conversions. If you look at the call stack you'll see that CodeDom uses serialization/deserialization and eventually uses reflection to set the value. Somewhere in that chain it loses the ability or context to attempt a conversion.

That said I am surprised you were able to set it via the designer. VS 2010 will not even show it in the drop down list. You can manually insert it into the designer.cs file but then when you get back to the designer, you'll get the same exception.

[Edit]
~~~~~~~~~

Yes I guessed correctly. This is indeed the case. You can easily reproduce this in your own code too:

C#
static void Main()
{
    Program obj = new Program();
    Test test = new Test();

    var mi = typeof(Program).GetMethod("set_Number");

    // the following line will throw
    mi.Invoke(obj, new object[] { test });
}

public int Number { get; set; }

class Test
{
    public static implicit operator int(Test t)
    {
        return 50;
    }
}


Note that instead of using a PropertyInfo, I am using a MethodInfo - because this is what the Visual Studio designer does too.
 
Share this answer
 
v2
Comments
Espen Harlinn 24-Feb-11 4:03am    
Very good reply, my 5
Nish Nishant 24-Feb-11 8:33am    
Thank you, Espen.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900