views:

45

answers:

1

I have the following Extension Method

Imports System.Runtime.CompilerServices
Namespace Extensions
    Public Module IntegerExtensions

        <Extension()>
        Public Function ToCommaDeliminatedNumber(ByVal int As Integer) As String

            Dim _input As String = int.ToString
            Select Case int
                Case Is > 99999 : Return _input.Remove(_input.Length - 3) & "k"
                Case Is > 9999 : Return Math.Round(Double.Parse(int / 1000), 1).ToString & "k"
                Case Is > 999 : Return String.Format("{0:N0}", int)
                Case Else : Return _input
            End Select

        End Function
    End Module
End Namespace

And in one of my classes I'm using

user.Reputation.ToCommaDeliminatedNumber

I am importing the Extensions Namespace into the Class, but the error I'm getting is...

'ToCommaDeliminatedNumber' is not a member of 'Integer?'.

Can anybody tell me what I might be missing here? I do have other Extension Methods for Strings and Dates that work exactly as expected... I'm just at a loss on this one.

+1  A: 

Judging from your error message it looks like user.Reputation is actually a Nullable(Of Integer), based on the trailing question mark ('Integer?'). Is that correct?

Your extension method is extending Integer, not Integer? (i.e., Nullable(Of Integer)), hence the error. So either provide an overload that handles Integer? or call Value on the nullable type:

user.Reputation.Value.ToCommaDeliminatedNumber()

You will need to check that it is not null (Nothing) otherwise an exception will be thrown. An overloaded method might look like this:

<Extension()>
Public Function ToCommaDeliminatedNumber(ByVal int As Integer?) As String

    Return int.GetValueOrDefault().ToCommaDeliminatedNumber()

End Function

In the case that it's null the default value of 0 would be displayed.

Ahmad Mageed
D'ur - Thanks for the second pair of eyes. The nullable integer was exactly the problem.
rockinthesixstring