Using a structure in the same way as a primitive type

  • Thread starter Thread starter Chris Bernholt via .NET 247
  • Start date Start date
C

Chris Bernholt via .NET 247

I'd like to create a structure such as:

Public Structure MyType
Private m_variable As String

Public Property Variable() As String
Get()
return m_variable
End Get
Set (ByVal Value As String)
If validateVariable(Value) Then
m_variable = Value
Else
Throw New ArgumentException("Variable invalid")
End If
End Set
End Property

Private Function validateVariable(ByVal theVar as String)
'Do validation here
End Function
End Structure

and be able to use it like

Dim mt as MyType
Try
mt = "123abc"
Catch
'Handle exception
End Try

instead of

Dim mt As MyType
Try
mt.Variable = "123abc"
Catch
'Handle exception
End Try

Is this possible, and if so, what changes do I need to make?

Thanks

-- Chris
 
Chris,
Is this possible, and if so, what changes do I need to make?

Currently no. In the next version (VS 2005) yes, thanks to operator
overloading.



Mattias
 
Chris,
In addition to the other's comments,

I would define a constructor, then you can do:
mt = New MyType("123abc")

Public Structure MyType

Public Sub New(ByVal value As String)
validateVariable(value)
m_variable = value
End Sub

Hope this helps
Jay
 
Back
Top