Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example use of TimeSpan.MinValue? Why would anyone use that in practice?

Tags:

c#

.net

timespan

I was using TimeSpans and found about TimeSpan.MinValue in MSDN. I was wondering why they include that directly in the class, or better yet: if there was a classic example of why/when you would want to use it. Of course it's good to know the value, but one can look that up.

I thought of stuff like subtracting other TimeSpans but it doesn't really make sense to me.

Any ideas? Thanks!!

like image 868
Gaspa79 Avatar asked Nov 07 '25 00:11

Gaspa79


2 Answers

One thing that comes to mind:

static TimeSpan FindMax(params TimeSpan[] intervals) {
    if (intervals.Length == 0)
        throw new ArgumentException("intervals collection is empty");
    var max = TimeSpan.MinValue;
    foreach (var interval in intervals) {
        if (interval > max)
            max = interval;
    }
    return max;
}
like image 123
Evk Avatar answered Nov 09 '25 17:11

Evk


One example I can give you is where it could be used as an alternative to a Nullable TimeSpan property in a class (TimeSpan is Nullable, by the way)

And you're displaying some text somewhere - that relies on something being "set" (or not).

Let's say a string that is showing how long something has been running.

Use a full property (with backing field) to achieve this:

Set the initial field's value to TimeSpan.MinValue which you can then use a public property to alter. Then, for the string you want to display, use your favourite PropertyChanged event handler (or other code) to update your view:

private TimeSpan _lengthOfTime = TimeSpan.MinValue;
public TimeSpan LengthOfTime
{
    get { return _lengthOfTime; }
    set
    {
        _lengthOfTime = value;
        OnPropertyChanged("LengthOfTimeString");
    }
}

public string LengthOfTimeString
{
    get
    {
        if (LengthOfTime == TimeSpan.MinValue)
        {
            return "The length of time has not been set.";
        }
        else
        {
            return LengthOfTime.ToString("YourFavouriteStringFormatHere");
        }
    }
}

When you then update your LengthOfTime property, it will call OnPropertyChanged (or whatever you use to update the UI) to get the LengthOfTimeString value, which is then re-calculated and displayed on your view.

This is only an example; and your scenario of what to use it for might be different.

I would suggest looking at https://msdn.microsoft.com/en-us/library/ms229614(v=vs.100).aspx, which tells you about how to implement INotifyPropertyChanged; if you're thinking of using Bindings in WPF/XAML/WinRT (if you don't know how to already).

like image 24
Geoff James Avatar answered Nov 09 '25 17:11

Geoff James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!