Support implicit/explicit conversion in C# for VB.NET

Today I hit an annoying problem with VB.NET using components written in C#. The basic problem is that I have an object called Field with a Value property of type object written in C#. The client code is written in VB.NET and wants to access the Field’s value without specifying the Value property, e.g.

Dim myField as Field = new Field()
myField.Value = 13

If CInt(myField) = 13 or myField = 13…

The initial problem is that a Field is not an int, so you’ll get an invalid cast, fair enough. So I implemented the implicit/explicit conversion operators available in C#.

Field myField = new Field();
myField.Value = 13

if ((int)myField==13)…

The above, written in C#, now works but the previous VB.NET still fails! The problem is that VB.NET simply doesn’t call op_Implicit/op_Explicit functions exposed by the C# code. Delving into the Visual Basic engine you can see that under the covers it use IConvertable to do all of its conversions. So if you want VB.NET to understand that House = 7 really means House.Number = 7 then you need to implement IConvertable in the C# component.

After implementing IConvertable the above code sprang into life.

Advertisements

One thought on “Support implicit/explicit conversion in C# for VB.NET

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s