Skip to content

Commit

Permalink
QuantityValue: Do not allow NaN value
Browse files Browse the repository at this point in the history
This prevents constructing any quantity with a NaN floating point value.
Decimal and integer types does not the concept of NaN (nor Infinity), so I'm
tempted to argue we should not allow those values either to be consistent with
quantities backed by decimal type.
  • Loading branch information
angularsen committed Oct 1, 2018
1 parent fb099e4 commit 81d4857
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
38 changes: 38 additions & 0 deletions UnitsNet/InternalHelpers/Guard.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Copyright (c) 2013 Andreas Gullberg Larsen ([email protected]).
// https://github.com/angularsen/UnitsNet
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using JetBrains.Annotations;

namespace UnitsNet.InternalHelpers
{
/// <summary>
/// Guard methods to ensure parameter values satisfy pre-conditions and use a consistent exception message.
/// </summary>
internal static class Guard
{
internal static double EnsureNotNaN(double value, [InvokerParameterName] string paramName)
{
if (double.IsNaN(value)) throw new ArgumentException("'NaN' is not a valid number.", paramName);
return value;
}
}
}
4 changes: 3 additions & 1 deletion UnitsNet/QuantityValue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@

// Operator overloads not supported in Windows Runtime Components, we use 'double' type instead

using UnitsNet.InternalHelpers;

#if !WINDOWS_UWP
namespace UnitsNet
{
Expand Down Expand Up @@ -55,7 +57,7 @@ public struct QuantityValue

private QuantityValue(double val)
{
_value = val;
_value = Guard.EnsureNotNaN(val, nameof(val));
_valueDecimal = null;
}

Expand Down

0 comments on commit 81d4857

Please sign in to comment.