Reputation: 789
I am fairly new to custom classes in VB.Net and am having a bit of an issue with assigning a value from my class to the class object. See code below:
Public Class NType
Public Const Small As Double = 1
Public Const Medium As Double = 2
Public Const Large As Double = 3
'Another thing I tried...
Public Shared ReadOnly Property _Small As Double
Get
Return Small
End Get
End Property
End Class
However as soon as I do:
Dim NType1 as NType = NType.Small
I get an error to say Value of type 'Double' cannot be converted to 'Harris.NType'
I assume there will be some sort of way to allow this (in a similar vein to how, say Color
works)
Upvotes: 0
Views: 72
Reputation: 54417
I think that, from the looks of it, what you actually want is an enumeration rather than a class.
Public Enum NType
Small
Medium
Large
End Enum
Dim nType1 As NType = NType.Small
You can specify the actual values but, generally, those values should be irrelevant and all that matters is that they're unique and don't change. By default, an enumeration is stored as an Integer
but you can specify any integral type. By default, the first value is equal to zero and each subsequent value is equal to 1 more than the previous one. You can specify one or more values if you need to though.
Public Enum NType As Short
Small = 1
Medium
Large
End Enum
The values still increment by 1 but will now start at 1 instead of zero. You should only do that if you will be using the same numeric values to represent the same data elsewhere and the two must match. Don't do it just because you can.
Upvotes: 3