| | | 1 | | using System; |
| | | 2 | | |
| | | 3 | | namespace Pozitron.Convert; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Conversion extensions to object |
| | | 7 | | /// </summary> |
| | | 8 | | public static class ObjectExtensions |
| | | 9 | | { |
| | | 10 | | /// <summary> |
| | | 11 | | /// It converts the object value to various IConvertible types. |
| | | 12 | | /// </summary> |
| | | 13 | | /// <typeparam name="T">The target IConvertible type</typeparam> |
| | | 14 | | /// <param name="value">The object value to be converted.</param> |
| | | 15 | | /// <param name="defaultValue">The default to be returned if conversion is not successful. By default it's the defau |
| | | 16 | | /// <param name="provider">An object that supplies culture-specific formatting information.</param> |
| | | 17 | | /// <returns>On success, it returns the converted value. On failure or null <see href="value" />, it returns the pro |
| | | 18 | | #if NET8_0_OR_GREATER |
| | | 19 | | [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(nameof(defaultValue))] |
| | | 20 | | #endif |
| | | 21 | | public static T? To<T>(this object? value, T? defaultValue = default, IFormatProvider? provider = null) where T : IC |
| | | 22 | | { |
| | 75 | 23 | | if (value is null) return defaultValue; |
| | | 24 | | |
| | | 25 | | try |
| | | 26 | | { |
| | 51 | 27 | | return (T?)System.Convert.ChangeType(value, typeof(T), provider); |
| | | 28 | | } |
| | 10 | 29 | | catch (Exception) |
| | | 30 | | { |
| | 10 | 31 | | } |
| | | 32 | | |
| | 10 | 33 | | return defaultValue; |
| | 41 | 34 | | } |
| | | 35 | | |
| | | 36 | | /// <summary> |
| | | 37 | | /// It converts the object value to various IConvertible struct types. |
| | | 38 | | /// </summary> |
| | | 39 | | /// <typeparam name="T">The target IConvertible struct type</typeparam> |
| | | 40 | | /// <param name="value">The object value to be converted</param> |
| | | 41 | | /// <param name="provider">An object that supplies culture-specific formatting information.</param> |
| | | 42 | | /// <returns>On success, it returns the converted value. On failure or null <see href="value" />, it returns null.</ |
| | | 43 | | public static T? ToNullable<T>(this object? value, IFormatProvider? provider = null) where T : struct, IConvertible |
| | | 44 | | { |
| | 36 | 45 | | if (value is null) return null; |
| | | 46 | | |
| | | 47 | | try |
| | | 48 | | { |
| | 24 | 49 | | return (T)System.Convert.ChangeType(value, typeof(T), provider); |
| | | 50 | | } |
| | 6 | 51 | | catch (Exception) |
| | | 52 | | { |
| | 6 | 53 | | } |
| | | 54 | | |
| | 6 | 55 | | return null; |
| | 18 | 56 | | } |
| | | 57 | | } |
| | | 58 | | |