Reputation: 1126
I need to cast, in the better way, two objects of two types of two custom-classes (in VB.Net):
The code:
Public Class pluto
Public Sub New(ByVal campoPippoPass As String)
_campoPippo = campoPippoPass
End Sub
Private _campoPippo As String = ""
Public Property campoPippo() As String
Get
Return Me._campoPippo
End Get
Set(ByVal value As String)
If Not Object.Equals(Me._campoPippo, value) Then
Me._campoPippo = value
End If
End Set
End Property
End Class
Public Class pippo
Public Sub New(ByVal campoPippoPass As String)
_campoPippo = campoPippoPass
End Sub
Private _campoPippo As String = ""
Public Property campoPippo() As String
Get
Return Me._campoPippo
End Get
Set(ByVal value As String)
If Not Object.Equals(Me._campoPippo, value) Then
Me._campoPippo = value
End If
End Set
End Property
End Class
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim a As New pippo("ciao")
' here I have the error 'invalid cast'
Dim c As pluto = CType(a, pluto)
MsgBox(c.campoPippo)
End Sub
How can I convert "c" into an "a" type object? Is there another way than writing the following?
Dim c As New pluto(a.campoPippo)
In the case of a more complex class, it could be more easy if there was a function for the conversion.
Upvotes: 0
Views: 5227
Reputation: 54999
Firstly, I'm assuming the line: Dim c As pluto = CType(b, pluto)
is a mistype and should actually be Dim c As pluto = CType(a, pluto)
?
You can't cast one class to another unless they're related. You might need to explain what you're trying to do otherwise my answer would be, why are you creating the different classes pluto
and pippo
if they seem to be identical? Just create the one class and create two objects of it.
If you do need separate classes, maybe they are related in some way and you could make pippo
inherit from pluto
? Or make both of them implement the same interface.
In general I'd also suggest that it might be worth translating your class/variable names to English since that might make it easier for people to understand what you're trying to do.
Upvotes: 1