Search code examples
c#timeouthttprequesttimespan

C# TimeSpan conversion in HttpRequestMessage Extension


I have the below static Extension class:

public static class HttpRequestExtensions
{
    private static string TimeoutPropertyKey = "RequestTimeout";

    public static void SetTimeout(
        this HttpRequestMessage request,
        TimeSpan? timeout)
        {
        if ( request == null )
            throw new ArgumentNullException (nameof (request));

        request.Properties[TimeoutPropertyKey] = timeout;
        }

        public static TimeSpan? GetTimeout(this HttpRequestMessage request)
        {
        if ( request == null )
            throw new ArgumentNullException (nameof (request));

        if ( request.Properties.TryGetValue (
                TimeoutPropertyKey,
                out var value)
            && value is TimeSpan timeout )
            return timeout;
        return null;
        }
}

Unfortunately, because of different environments, I can't use the out var value (C# versions etc etc) and I am compelled to change it, same as the value is TimeSpan timeout (can't change parameters in IDE, C# version etcetc although this is perfectly good code).

I have come up with the below

public static TimeSpan? GetTimeout(this HttpRequestMessage request)
{
    object value;
    TimeSpan ts = new TimeSpan();

    if ( request == null )
        throw new ArgumentNullException (nameof (request));

    if ( request.Properties.TryGetValue (
            TimeoutPropertyKey,
            out value)
        && value.GetType () == typeof (Timeout) )
        ts = TimeSpan.Parse (value.ToString());
    return ts;
}

Could someone advise me if this correct, and if not, suggest an alternative? Thank you very much..


Solution

  • You can simply test whether object contains a boxed TimeSpan using is, and then unbox it using a cast:

    public static TimeSpan? GetTimeout(this HttpRequestMessage request)
    {
        if ( request == null )
            throw new ArgumentNullException (nameof (request));
    
        object value;
        if ( request.Properties.TryGetValue(TimeoutPropertyKey, out value)
            && value is TimeSpan )
        {
            return (TimeSpan)value;
        }
        return null;
    }
    

    You can even use as with a TimeSpan?. This results in a null value if value doesn't contain a boxed TimeSpan.

    public static TimeSpan? GetTimeout(this HttpRequestMessage request)
    {
        if ( request == null )
            throw new ArgumentNullException (nameof (request));
    
        object value;
        if ( request.Properties.TryGetValue(TimeoutPropertyKey, out value) )
        {
            return value as TimeSpan?;
        }
        return null;
    }