1

I've written the following Extension Method

    <Extension()>
    Public Function ToUtcIso8601(ByVal dt As Date) As String
        Return String.Format("{0:s}Z", dt)
    End Function

But I also need a Nullable version of the same method... how exactly do I do this?

This is what I was thinking, but I'm not sure if this is the right way

    <Extension()>
    Public Function ToUtcIso8601(ByVal dt As Date?) As String
        Return If(dt, Nothing).ToUtcIso8601()
    End Function

or another option

    <Extension()>
    Public Function ToUtcIso8601(ByVal dt As Date?) As String
        Return If(Not dt Is Nothing, ToUtcIso8601(dt), Nothing)
    End Function

I'm just not sure the "right" way to do this.

Edited

This actually works, But...

    Public Function ToUtcIso8601(ByVal dt As Date?) As String
        Return If(Not dt Is Nothing, ToUtcIso8601(dt.Value), Nothing)
    End Function

Is this the right way to do this?

Chase Florell
  • 46,378
  • 57
  • 186
  • 376

1 Answers1

2

I'd go for the second option. Unfortunately, when using extension methods on a Date struct, Date? extension methods are not applicable, otherwise you could just declare one extension for the Date? type. You will have to take a similar approach to the one you already have in order to support both types.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • unfortunately my second option keeps crashing the WebDev service – Chase Florell Nov 10 '10 at 03:17
  • You'll need to supply a stack trace or something then. – cdhowie Nov 10 '10 at 03:19
  • 2
    Shouldn't the line read: `Return If(Not dt Is Nothing, ToUtcIso8601(dt.value), Nothing)` – David Nov 10 '10 at 03:44
  • debugger looks like it's creating an infinite loop – Chase Florell Nov 10 '10 at 03:47
  • Ah yes, David is right. I wasn't sure if VB automatically extracted nullable values, but that's actually not even relevant here. You are recursing into the method over and over by not using dt.Value -- you are supplying a Date?, and that's causing the infinite recursion. – cdhowie Nov 10 '10 at 03:50
  • I added the .Value to no avail – Chase Florell Nov 10 '10 at 03:52
  • Then something else is wrong. Make sure that the service was restarted if necessary and look for another stack trace. – cdhowie Nov 10 '10 at 03:53
  • ok, I got it. Turns out I was calling it incorrectly in the initial call. I was using `ToUtcIso8601(dt)` instead of `dt.ToUtcIso8601()` – Chase Florell Nov 10 '10 at 04:05
  • i'm still wondering if I'm doing it right, or just "doing it". – Chase Florell Nov 10 '10 at 04:12
  • 1
    @rockinthesixstring: This looks good to me, however I've always found the .HasValue property of a nullable type cleaner to use in these sorts of situations; I would use something like: Return If(dt.HasValue, ToUtcIso8601(dt.Value), Nothing) – DanP Nov 12 '10 at 11:00