Vb.net – Type casting in VB .NET

castingvb.net

I am adding a feature to an existing VB .Net application that involves retrieving data from a .Net web service. The web service returns an array of Locations. A Location is pretty simple, it has 3 properties – an integer and two strings.

So that the rest of my application does not have to be dependent on this web service, I would like to create my own Location type within my application. My thought is I could call a method that returns a generic list of my Location type which internally calls the web service and populates the list I return. That way, if the data source for Locations changes in the future to something other than the web service, I only have to fix the method instead of fixing all the callers.

So I created my own Location that has identical properties as the service Location. But I don’t seem to be able to cast the array of service locations into a generic list of my locations. I also tried casting a single service Location into one of my Locations and that didn’t work either.

So is casting an option or do I have to loop through each service Location and assign each property to a new one of my Locations? Or is there a completely different way to go about this?

Best Solution

By default you will not be able to cast one Location to another. They are completely unrelated types and thus cannot be the subject of casting. You can make it possible to cast though by defining a custom operator for the application version of CType.

' Location for application
Public Class Location
  ...
  Public Shared Operator Widening CType(p1 as Namespace.Of.WebService.Location) As Location
    Dim loc = ConvertWebServiceLocationToApplicationLocation
    return loc
  End Operator
End Class

This allows you to now do a CType operation between a WebService Location the Application Location.

Casting the array though, simply won't be possible. There is no way to define a conversion operator for arrays so they can't use the above trick. But you can write a quick and dirty function for this purpose

Public Shared Function ConvertArray(ByVal arr As Namespace.Of.WebServiec.Location()) As Location()
  Dim newArray(arr.Length) As Location
  For i as Integer = 0 To arr.Length - 1
    newArray(i) = CType(arr(i), Location)
  Next
  return newArray
End Function