views:

23

answers:

1

I am having a structure that is actually a simple byte with more functionality.

I defined it this way:

Structure DeltaTime

    Private m_DeltaTime As Byte
    Public ReadOnly DeltaTime As Byte
        Get
            Return m_DeltaTime
        End Get
    End Property

End Structure

I want to have these two functionalities:

Public Sub Main
    Dim x As DeltaTime = 80 'Create a new instance of DeltaTime set to 80
    Dim y As New ClassWithDtProperty With { .DeltaTime = 80 }
End Sub

Is there a way to achieve this?

If there would be a way to inherit from Structure I would simply inherit from Byte adding my functionality, basically I just need a byte Structure with custom functionality.

My question is also valid when you want to define your new singleton member value-types (like, you want to define a nibble-type for instance etc.) and you want to be able to set it with an assignment to number or other language typed representation.

In other words, I want to be able to do define the following Int4 (nibble) stucture and use it as follows:

Dim myNibble As Int4 = &HF 'Unsigned
+2  A: 

Create a conversion operator, e.g.

Structure DeltaTime

    Private m_DeltaTime As Byte
    Public ReadOnly Property DeltaTime() As Byte
        Get
            Return m_DeltaTime
        End Get
    End Property

    Public Shared Widening Operator CType(ByVal value As Byte) As DeltaTime
        Return New DeltaTime With {.m_DeltaTime = value}
    End Operator

End Structure

UPDATE:

For your proposed Int4 type I strongly suggest that you make it a Narrowing operator instead. This forces the user of your code to cast explicitly, which is a visual hint that the assignment might fail at runtime, e.g.

Dim x As Int4 = CType(&HF, Int4) ' should succeed
Dim y As Int4 = CType(&HFF, Int4) ' should fail with an OverflowException
Christian Hayter
I am asking if you can make your first line work, I want to create a new instance of DeltaTime from this 80 constant. I guess the answer is "No you can't", but I think the same answer is still valid for C# as well.
Shimmy
I understand now. Answer re-written.
Christian Hayter
Shimmy
That's not how the VB.NET language works I'm afraid. If you try to stuff a large integer into a smaller integer, then it (a) requires you to add an explicit conversion operator, and (b) discovers any conversion failures at runtime.
Christian Hayter