Same property, different types
-
03-07-2019 - |
Question
Let's say you have a class with a Uri property. Is there any way to get that property to accept both a string value and a Uri? How would you build it?
I'd like to be able to do something like one of the following, but neither are supported (using VB, since it lets you specify type in the Set declaration for the 2nd one):
Class MyClass
Private _link As Uri
'Option 1: overloaded property
Public Property Link1 As Uri
Get
return _link
End Get
Set(ByVal value As Uri)
_link = value
End Set
End Property
Public Property link1 As String
Get
return _link.ToString()
End Get
Set(Byval value As String)
_link = new Uri(value)
End Set
End Property
' Option 2: Overloaded setter
Public Property link2 As Uri
Get
return _link
End Get
Set(Byval value As Uri)
_link = value
End Set
Set(Byval value As String)
_link = new Uri(value)
End Set
End Class
Given that those probably won't be supported any time soon, how else would you handle this? I'm looking for something a little nicer than just providing an additional .SetLink(string value)
method, and I'm still on .Net2.0 (though if later versions have a nice feature for this, I'd like to hear about it).
I can think of other scenarios where you might want to provide this kind of overload: a class with an SqlConnection member that lets you set either a new connection or a new connection string, for example.
Solution
Alternatively, you can of course forego overloading and just name the properties appropriately:
Public WriteOnly Property UriString() As String
Set(ByVal value As String)
m_Uri = new Uri(value)
End Set
End Property
Of course you don't have to make this WriteOnly
but it seems appropriate.
OTHER TIPS
I think you just need to provide an accompanying
Public Sub SetLink(ByVal value as String)
_link = new Uri(value)
End Sub
Nothing nicer is available, AFAIK.
Let's say you have a class with a Uri property. Is there any way to get that property to accept both a string value and a Uri?
No because this would mean having two getters that vary only in their return type and this isn't allowed in .NET.
I would use the Uri
method exclusively and perhaps create a convenienec method to set the URI
property, given a string. However, since the conversion from String
to URI
is straightforward, even this might be unnecessary.
You can't have one property like that, but you could create two properties which both manipulated the same underlying field - just like Height/Width/Size in Windows Forms.