Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

Non-related implicit type casting

2012-04-12

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.

Categories: VB.NET

Leave a Reply

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



En kopp kaffe!

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

Bjud på en kopp kaffe!

Om...

Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   linktr.ee/hesselbom   |   winsoft.se   |   80tal.se   |   Filmtips