Non-related implicit type casting

As always, I use Visual Basic in strict mode. I have this function that expects a Foo array:

Sub DoSomething(X() As Foo)
   Console.WriteLine(X.Length)
End Sub

What I’m showing here is true for single variables too, but I am showing this using arrays. This cannot be called using an Integer array as follows:

DoSomething({1, 2, 3})

Adding a Integer constructor to the Foo class does not help. However, you can add a widening operator to the Foo class, and define how an implicit conversion is done, like so:

Public Class Foo

   Private mX As Integer

   Public Sub New(X As Integer)
      Me.mX = X
   End Sub

   Shared Widening Operator CType(X As Integer) As Foo
      Return New Foo(X)
   End Operator

End Class

Now, both the above method call is accepted. And because this also works on arrays, this simple line constructs three Foo objects:

Dim X() As Foo = {4, 5, 6}

The equivalent with a single (non arrayed) object would look like this:

Dim Y As Foo = 7

The opposite to Widening is called Narrowing and is used to define explicit type casts.

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll:

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Comments

Important information: If you have not commented before, your comment will be reviewed before it is published. This means that you will not see it immediately, but I have received it. This is not because I want to filter comments, but because I want to prevent spam and advertising.

Leave a Reply

Your email address will not be published. Required fields are marked *