Search code examples
asp.netvb.netextension-methodsnullable

How to write extension methods for both Nullable and Not Nullable


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?


Solution

  • 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.