Reputation: 1
I am trying to access a property of a class (let's call it 'A') that is built to handle a list of some other class (call it 'B'), from any 'B' member. But I don't want this property to be shared (static) so any instance of 'A' can have a different value of this property, and any 'B' accesses the property of the 'A' it belongs to.
eg
**class A**
private Items as list (of B)
...
...
public property ThisProperty() as Integer
**end class**
**class B**
...
public function UseThisProperty() as string
If ThisProperty=1 then
return "this"
elseif ThisProperty=2 then
return "other"
else
return "sth else"
end function
**End class**
I don't know how and if that is possible, but any thoughts will be appreciated.
Upvotes: 0
Views: 41
Reputation: 2167
There are some ways to solve this. However, the solution highly depends on the context and questions like Who creates object A/B?, what is the lifecycle of A/B?, who is the client of A/B? How coupled are A/B?. Nevertheless here are some solutions:
Public Class A
Public Property ThisProperty() As Integer
End Class
Inject object A into B via constructor. Helpful if A and B are closely coupled and if it´s not a drawback that they are. Also when creating B A must alreday exist:
Public Class B
Private _a As A
Public Sub New(a As A)
_a = a
End Sub
Public Function UseThisProperty() As String
If _a.ThisProperty = 1 Then
Return "this"
ElseIf _a.ThisProperty = 2 Then
Return "other"
Else
Return "sth else"
End If
End Function
End Class
Inject just the value of A.ThisProperty
into B via constructor. Helpful to decouple A and B and there is only one(few) property which is used by B:
Public Class B
Private _aThisProperty As Integer
Public Sub New(thisProperty As Integer)
_aThisProperty = thisProperty
End Sub
Public Function UseThisProperty() As String
If _aThisProperty = 1 Then
Return "this"
ElseIf _aThisProperty = 2 Then
Return "other"
Else
Return "sthelse"
End If
End Function
End Class
Inject A when calling B.UseThisProperty. This is helpful if there is a class C which decouples A and B:
Public Class D
Public Function UseThisProperty(a As A) As String
If a.ThisProperty = 1 Then
Return "this"
ElseIf a.ThisProperty = 2 Then
Return "other"
Else
Return "sth else"
End If
End Function
End Class
Inject A into B via public setter. This is helpful if A is not yet determined when creating object B:
Public Class B
Public Property a As A
Public Function UseThisProperty() As String
If a.ThisProperty = 1 Then
Return "this"
ElseIf a.ThisProperty = 2 Then
Return "other"
Else
Return "sth else"
End If
End Function
End Class
There are other soltion like a Mediator
class which could decouple A and B completely etc.
Upvotes: 1