| | 1 | | namespace Common.Core.Converters; |
| | 2 | |
|
| | 3 | | /// <summary>Helper methods to convert data types to other data types.</summary> |
| | 4 | | public 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 ) |
| 15 | 12 | | { |
| 19 | 13 | | if( value is null or DBNull ) { return defaultValue; } |
| | 14 | | try |
| 13 | 15 | | { |
| 13 | 16 | | return (T?)(T)System.Convert.ChangeType( value, |
| 13 | 17 | | Nullable.GetUnderlyingType( typeof( T ) ) ?? typeof( T ) ); |
| | 18 | | } |
| 3 | 19 | | catch { return defaultValue; } |
| 15 | 20 | | } |
| | 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 ) |
| 13 | 27 | | { |
| 13 | 28 | | char? data = Convert<char?>( value, null ); |
| 17 | 29 | | if( data is null ) { return null; } |
| 11 | 30 | | string strVal = data.ToString()!; |
| 11 | 31 | | bool ok = StringConverter.TryParse( ref strVal, out bool result ); |
| 11 | 32 | | return ok ? result : null; |
| 13 | 33 | | } |
| | 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 ) |
| 2 | 39 | | { |
| 2 | 40 | | DateTime? data = Convert<DateTime?>( value, null ); |
| 4 | 41 | | if( data is null ) { return null; } |
| 1 | 42 | | return DateOnly.FromDateTime( data.Value ); |
| 2 | 43 | | } |
| | 44 | | } |