user-63873687
user-63873687

Reputation: 105

VB.Net function that accepts nullables?

I wanted to make a sub that manipulated nullables. The idea is for it to take in any nullable variable, and if it has a value, then overwrite a different value. Here is what I wrote:

Dim a as int? = 0
Dim b as int? = 1

Sub ApplyChange(Byref Old As Nullable, ByRef Change as Nullable)
    If Change.HasValue Then
        Old = Change
    End IF
End Sub

ApplyChange(a, b)

The problem is, I get an error '"HasValue is not a member of Nullable' and 'int? cannot be converted to Nullable'. What's going on here? How do I go about making a sub that accepts only nullables?

Upvotes: 1

Views: 42

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54417

Don't use the Nullable class as your parameter type. Use the Nullable(Of T) structure, which is what your variables are declared as. This:

Dim a As Integer? = 0
Dim b As Integer? = 1

is shorthand for this:

Dim a As Nullable(Of Integer) = 0
Dim b As Nullable(Of Integer) = 1

That means that your method can be like this:

Sub ApplyChange(Of T As Structure)(ByRef Old As Nullable(Of T), Change As Nullable(Of T))
    If Change.HasValue Then
        Old = Change
    End If
End Sub

Again, no ByRef needed if you're not setting the argument or any of its members.

Using the same shorthand:

Sub ApplyChange(Of T As Structure)(ByRef Old As T?, Change As T?)
    If Change.HasValue Then
        Old = Change
    End If
End Sub

Upvotes: 3

Related Questions