views:

107

answers:

2

I've written a small utility function for our base page, it works fine in most cases, but if it's called in the form SetDropDownValue(dropdown, Nothing, True) I have to specify the type T.

Since the compiler only requires a type specified when the type is not used, I'm wondering if there is a better way to write the code.

The method is as follows:

Protected Sub SetDropDownValue(Of T As Structure)(ByVal target As DropDownList, ByVal value As Nullable(Of T), ByVal bindFirst As Boolean)

    If target Is Nothing Then
        Throw New ArgumentNullException("target")
    End If

    If bindFirst Then
        target.DataBind()
    End If

    If value.HasValue Then
        target.SelectedValue = value.Value.ToString()
    Else
        target.SelectedIndex = 0
    End If

End Sub

What is a better way to code this method?

A: 

If the value is Nothing then it doesn't really matter what the type would be, right? So I'd write another method:

Protected Sub ClearDropDownValue(ByVal target As DropDownList, ByVal bindFirst As Boolean)
    SetDropDownValue(target, CType(Nothing, Nullable(Of Integer)), bindFirst)
End Sub

Apologies if my VB syntax isn't quite right - but basically just make it a helper method which calls SetDropDownValue with a Nothing of an arbitrary nullable type.

Jon Skeet
A: 

Unfortunately you will be stuck with having to specify the type when you pass Nothing. The VB value Nothing has no type in the compiler and thus cannot be used to infer a type. If you're depending on type inference to avoid specifically adding type parameters you cannot pass Nothing to the parameter that would allow the compiler to infer the type.

JaredPar
I thought that might be the case, I was just hoping that there might just be something that I was missing with generics.
ilivewithian