< Summary - Core.Tests

Information
Class: Common.Core.Converters.Generic
Assembly: Common.Core
File(s): D:\a\NuGetPackages\NuGetPackages\src\Common\Core\Converters\Generic.cs
Tag: 3_8508158812
Line coverage
100%
Covered lines: 19
Uncovered lines: 0
Coverable lines: 19
Total lines: 44
Line coverage: 100%
Branch coverage
92%
Covered branches: 13
Total branches: 14
Branch coverage: 92.8%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
Convert(...)87.5%88100%
CharToBool(...)100%44100%
DateTimeToDateOnly(...)100%22100%

File(s)

D:\a\NuGetPackages\NuGetPackages\src\Common\Core\Converters\Generic.cs

#LineLine coverage
 1namespace Common.Core.Converters;
 2
 3/// <summary>Helper methods to convert data types to other data types.</summary>
 4public static class Generic
 5{
 6  /// <summary>Safe converting to any type.</summary>
 7  /// <typeparam name="T">Type of object to convert.</typeparam>
 8  /// <param name="value">Value to try and convert.</param>
 9  /// <param name="defaultValue">Default value, sets the type of the returned value.</param>
 10  /// <returns>The converted value, or defaultValue if any error occurs.</returns>
 11  private static T? Convert<T>( object? value, T defaultValue )
 1512  {
 1913    if( value is null or DBNull ) { return defaultValue; }
 14    try
 1315    {
 1316      return (T?)(T)System.Convert.ChangeType( value,
 1317          Nullable.GetUnderlyingType( typeof( T ) ) ?? typeof( T ) );
 18    }
 319    catch { return defaultValue; }
 1520  }
 21
 22  /// <summary>Converts a char object to a 3-state boolean type.</summary>
 23  /// <param name="value">Value to try and convert.</param>
 24  /// <returns><see langword="null"/> is returned if the value could not be converted,
 25  /// <see langword="true"/> if the value is Y, y, or 1, otherwise <see langword="false"/>.</returns>
 26  public static bool? CharToBool( object value )
 1327  {
 1328    char? data = Convert<char?>( value, null );
 1729    if( data is null ) {  return null; }
 1130    string strVal = data.ToString()!;
 1131    bool ok = StringConverter.TryParse( ref strVal, out bool result );
 1132    return ok ? result : null;
 1333  }
 34
 35  /// <summary>Converts a DateTime object to a DateOnly type.</summary>
 36  /// <param name="value">Value to try and convert.</param>
 37  /// <returns><see langword="null"/> is returned if the value could not be converted.</returns>
 38  public static DateOnly? DateTimeToDateOnly( object value )
 239  {
 240    DateTime? data = Convert<DateTime?>( value, null );
 441    if( data is null ) { return null; }
 142    return DateOnly.FromDateTime( data.Value );
 243  }
 44}