C# Client Library
A C# Client Library for the AnalyzeRe REST API
Loading...
Searching...
No Matches
TypeExtensionMethods.cs
Go to the documentation of this file.
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
6{
8 public static class TypeExtensionMethods
9 {
12 public static string NiceTypeName(this Type t)
13 {
14 // TODO: Handle nested class names (e.g. Perspective.Base) to show the parent class in the name
15 if (!t.IsGenericType)
16 return t.Name;
17 string genericTypeName = t.GetGenericTypeDefinition().Name;
18 genericTypeName = genericTypeName.Substring(0,
19 genericTypeName.IndexOf('`'));
20 string genericArgs = String.Join(",",
21 t.GetGenericArguments().Select(NiceTypeName).ToArray());
22 return genericTypeName + "<" + genericArgs + ">";
23 }
24
25 private static readonly HashSet<Type> IntegerTypes = new HashSet<Type>
26 {
27 typeof(Byte),
28 typeof(SByte),
29 typeof(UInt16),
30 typeof(UInt32),
31 typeof(UInt64),
32 typeof(Int16),
33 typeof(Int32),
34 typeof(Int64)
35 };
36
40 public static bool IsIntegerType(this Type t)
41 {
42 return IntegerTypes.Contains(t) ||
43 IntegerTypes.Contains(Nullable.GetUnderlyingType(t));
44 }
45
46 private static readonly HashSet<Type> NumericTypes = new HashSet<Type>(IntegerTypes)
47 {
48 typeof(Decimal),
49 typeof(Double),
50 typeof(Single),
51 };
52
56 public static bool IsNumeric(this Type t)
57 {
58 return NumericTypes.Contains(t) ||
59 NumericTypes.Contains(Nullable.GetUnderlyingType(t));
60 }
61
67 public static bool AlmostEquals(this double d1, double d2,
68 double tolerance = 1E-14)
69 {
70 return d1.Equals(d2) ||
71 Math.Abs((d1 - d2) / Math.Max(Math.Abs(d1), Math.Abs(d2))) <= tolerance;
72 }
73
82 public static bool AlmostEquals(this DateTime dt1, DateTime dt2, TimeSpan? tolerance = null)
83 {
84 // Note: TimeSpan.FromMilliseconds doesn't take fractional milliseconds, so we must use Ticks.
85 tolerance = tolerance ?? TimeSpan.FromTicks(1000);
86 return (dt1.ToUniversalTime() - dt2.ToUniversalTime()).Duration() <= tolerance;
87 }
88 }
89}
Utilities used to format types and properties in a manner suitable to output in error messages,...
static string NiceTypeName(this Type t)
Produces a human readable string representation of the provided type name, with special consideration...
static bool AlmostEquals(this double d1, double d2, double tolerance=1E-14)
Determines whether two doubles are equivalent within the specified tolerance.
static bool IsIntegerType(this Type t)
Determines whether a property is an integer type.
static bool IsNumeric(this Type t)
Determines whether a property is numeric.
static bool AlmostEquals(this DateTime dt1, DateTime dt2, TimeSpan? tolerance=null)
Determines whether two dates are equal within the supported precision.