0

How do I convert this into C# 6 Null Conditional Check?

var durationhours = product.ProductAudioAsset.TotalLengthInSeconds != null
    ? (short?)TimeSpan.FromSeconds(product.ProductAudioAsset.TotalLengthInSeconds.Value).TotalHours
    : null;

where TotalLengthInSeconds is nullable short

5
  • I would use an extra temporary variable for clarity. Why do you think a null conditional is the way to go? Commented Jun 23, 2016 at 0:41
  • stackoverflow.com/questions/31811392/… Commented Jun 23, 2016 at 0:41
  • 1
    Why are you working with short? Stay with double - it's more precise and faster. Commented Jun 23, 2016 at 0:47
  • @ClickRick , Are you suggesting that I shouldn't consider using C# 6 null conditional check for this case? Commented Jun 23, 2016 at 0:51
  • @Enigmativity, legacy issue. Commented Jun 23, 2016 at 0:52

1 Answer 1

5

You could create an extension method to help:

public static short SecondsAsTotalHours(this short value)
{
    return (short)TimeSpan.FromSeconds(value).TotalHours;
}

Then you can do this:

var durationhours = product.ProductAudioAsset.TotalLengthInSeconds?.SecondsAsTotalHours();
Sign up to request clarification or add additional context in comments.

1 Comment

This is a good answer. I would rename TimeSpanFromSeconds to SecondsAsTotalHours or something similar though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.